Python快速入门——面向对象(上)
A、类和对象
1、创建类和对象
个人感觉Python的类和Java的类写法类似
class  Cat:
    def eat(self):  # 方法
        print('吃鱼')
cat = Cat()         # 创建对象
cat.eat()           # 调用方法
构造方法方法里面有一个self参数,我的理解是这个参数类似于Java里面的this关键字。
Python还可以给对象添加属性
# 添加属性
对象名.新的属性 = 值
# 调用属性
对象名.属性名
B、构造方法和析构方法
1、无参构造方法
class  Cat:
    def __init__(self):
        print('构造方法')
cat = Cat()         # 创建对象
2、有参构造方法
class  Cat:
    def __init__(self, color):
        self.color = color
cat = Cat('白色')         # 创建对象并传递参数
print(cat.color)    # 调用属性值
3、析构方法
Python在创建对象时,会默认调用__init__(构造方法),当删除一个对象来释放类占用的资源的时候就会调用__del__(析构方法)
class  Cat:
    def __init__(self, color):
        self.color = color
    def __del__(self):
        print('*'*10)
cat = Cat('白色')         # 创建对象
手动释放类占用的资源,调用__del__语句:
class  Cat:
    def __init__(self, color):
        self.color = color
    def __del__(self):
        print('*'*10)
cat = Cat('白色')         # 创建对象
del cat             # 手动释放资源
print('释放完毕')
C、self语句
前面好几次用到了self,详细说明一下
在方法的定义中,第一个参数永远是self,self的字面意思是自己,表示的是对象自己,可以理解为Java中的this关键字。当某个对象调用方法的时候,Python解释器会把这个对象作为第一个参数传递给self,我们只需要传递后面的参数就可以了。
class  Animal:
    def __init__(self, name):
        self.name = name
    def setColor(self, color):
        self.color = color
    def setFood(self, food):
        self.food = food
    def eat(self):
        print(self.color+'的'+self.name+'在吃'+self.food)
animal = Animal('猫咪')
animal.setColor('白色')
animal.setFood('猫粮')
animal.eat()
运行结果:白色的猫咪在吃猫粮
D、运算符重载
Python里的运算符实际调用的是对象的方法,例如,+ 运算符是类里面的 __add__ 方法,当调用 + 实现运算的时候,实际调用的是 __add__ 方法。
运算符重载方法
| 方法 | 说明 | 何时调用方法 | 
|---|---|---|
__add__ | 
加法运算 | 对象加法:x+y,x+=y | 
__sub__ | 
减法运算 | 对象减法:x-y,x-=y | 
__mul__ | 
乘法运算 | 对象乘法:xy,x=y | 
__truediv__ | 
除法运算 | 对象除法:x/y,x/=y | 
__mod__ | 
求余运算 | 对象求余:x%y,x%=y | 
__bool__ | 
真值运算 | 测试对象是否为真值:boo(x) | 
__repr__、__str__ | 
打印、转换 | print(x),repr(x),str(x) | 
__contains__ | 
成员测试 | item in x | 
__getitem__ | 
索引、分片 | x[i],x[i:j],没有__iter__的for循环等 | 
__setitem__ | 
索引赋值 | x[i] = 值,x[i:j] = 序列对象 | 
__delitem__ | 
索引和分片删除 | del x[i],del x[i:j] | 
__len__ | 
求长度 | len(x) | 
__iter__、__next__ | 
迭代 | iter(x),next(x),for 循环等 | 
__eq__、__ne__ | 
相等测试、不等测试 | x == y,x != y | 
__ge__、__gt__ | 
大于等于测试,大于测试 | x >= y,x > y | 
__le__、__lt__ | 
小于等于测试,小于测试 | x <=y,x < y | 
1、加减乘除取余运算重载
class Nnumber:
    def __init__(self, num):
        self.data = num
    def __add__(self, other):
        num = self.data + other.data
        return num
    def __sub__(self, other):
        num = self.data - other.data
        return num
    def __mul__(self, other):
        num = self.data * other.data
        return num
    def __truediv__(self, other):
        num = self.data / other.data
        return num
    def __mod__(self, other):
        num = self.data % other.data
        return num
n1 = Nnumber(200)
n2 = Nnumber(100)
print(n1+n2)    # 相当于 n1.__add__(n2)
print(n1-n2)    # 相当于 n1.__sub__(n2)
print(n1*n2)    # 相当于 n1.__mul__(n2)
print(n1/n2)    # 相当于 n1.__truediv__(n2)
print(n1%n2)    # 相当于 n1.__mod__(n2)
运行结果:
300
100
20000
2.0
0
2、索引和分片重载
和索引和分片重载相关的方法有三个:
__getitem__:索引、分片__setitem__:索引赋值__delitem__:索引和分片删除
1、__getitem__方法
当对实例对象执行索引、分片或者for迭代操作的时候,会自动调用__getitem__方法。
class Demo:
    def __init__(self, v):
        self.data = v
    def __getitem__(self, index):
        return self.data[index]
d = Demo([1, 2, 3, 4, 5])
print(d[1])     # 返回单个值
print(d[:])     # 返回全部的值
print(d[:2])    # 返回部分值
for i in d:     # for 循环迭代
    print(i)
运行结果:
2
[1, 2, 3, 4, 5]
[1, 2]
1
2
3
4
5
2、__setitem__方法
class Demo:
    def __init__(self, v):
        self.data = v
    def __setitem__(self, index, value):
        self.data[index] = value
d = Demo([1, 2, 3, 4, 5])
d[0] = 'smcs'
print(d.data)
d[1:5] = ['s', 'm', 'c', 's']
print(d.data)
运行结果:
['smcs', 2, 3, 4, 5]
['smcs', 's', 'm', 'c', 's']
3、__delitem__方法
在这里插入代码片class Demo:
    def __init__(self, v):
        self.data = v
    def __delitem__(self, index):
        del self.data[index]
d = Demo([1, 2, 3, 4, 5])
del d[0]
print(d.data)
del d[1:2]
print(d.data)
运行结果:
[2, 3, 4, 5]
[2, 4, 5]
3、定制对象的字符串形式
重载__repr__和__str__方法可以定义对象转换为字符串的形式,在执行print、str、repr及交互模式下直接显示对象会调用__repr__和__str__方法。
1、只重载__str__方法
如果只重载__str__方法,只有str和print函数可以调用这个方法进行转换。
class Demo:
    def __str__(self):
        return '__str__'
d = Demo()
print(d)
print(str(d))
print(repr(d))
运行结果:
__str__
__str__
<__main__.Demo object at 0x000001A26767C390>
2、只重载__repr__方法
重载__repr__方法,可以保证在各种操作下都能正确访问。
class Demo:
    def __repr__(self):
        return '__str__'
d = Demo()
print(d)
print(str(d))
print(repr(d))
运行结果:
__str__
__str__
__str__
3、同时重载__repr__和__str__方法
如果同时重载__repr__和__str__方法,则str和print函数调用__str__方法。交交互模式下直接显示对象和repr函数调用的是__repr__方法。
class Demo:
    def __repr__(self):
        return '__repr__'
    def __str__(self):
        return '__str__'
d = Demo()
print(d)
print(str(d))
print(repr(d))
运行结果:
__str__
__str__
__repr__
                                    
                    
                
                
            
        
浙公网安备 33010602011771号