为对象动态的添加属性和方法
添加属性
对象名.属性 = 对应类型的数据
VIP.name = "XiaoMing"
添加方法
首先要先导入MethodType,然后定义符合需求的方法,对象名.方法名(自定义) = MethodType(之前定义的方法名, 对象名)
from types import MethodType
#定义跑这一方法
def run(self):
print("正在跑")
#单独为猫这一对象添加跑这一方法
cat.run = MethodType(run, cat)
@property修饰语
对写入的属性进行限制
__slots__ = ("属性名","属性名")
读写保护
在为对象进行相应数据的读写时,考虑的其安全性和以便达到数据过滤的效果,需要对每个属性使用get,set方法进行读写。
注意:
如果读写的时候,方面名相同,没有修饰语则上面的方法会被下面同名的方法覆盖。
get方法要用@property;set方法要用@方法名.setter
重载运算符
实现对象的算数运算或比较
class Number(object):
def __init__(self, num):
self.num = num
#重写乘方魔法方法
def __pow__(self, power, modulo=None):
return (int(str(self.num)) ** power)
#重写比较魔法方法
def __lt__(self, other):
if self.num < other.num:
print(str(self.num) + "is smaller than" + str(other.num) )
else:
print(str(self.num) + "is not smaller than" + str(other.num) )