一,动态给类添加方法
在一个类外去添加属性时,我们可以通过添加 from types import MethodType 然后进行引用就可以实现在打印时仍能使用 类名.属性()的方式
案例:
from types import MethodType
class Cat(object):
pass
cat = Cat()
cat.name="tom"
def say(self):
print("my name is "+self.name)
def run(self):
print(self.name+"我正在跑")
cat.run = MethodType(run,cat)
cat.speak = MethodType(say,cat)
cat.speak()
cat.run()
二,运算符重载
类的专有方法:
Method Overloads Call for
__init__ 构造函数 X=Class()
__del__ 析构函数 对象销毁
__add__ + X+Y,X+=Y
__or__ | X|Y,X|=Y
__repr__ 打印转换 print X,repr(X)
__str__ 打印转换 print X,str(X)
__call__ 调用函数 X()
__getattr_ 限制 X.undefine
__setattr__ 取值 X.any=value
__getitem__ 索引 X[key],For If
__len__ 长度 len(X)
__cmp__ 比较 X==Y,X
__lt__ 小于 X
__eq__ 等于 X=Y
__radd__ Right-Side + +X
__iadd__ += X+=Y
__iter__ 迭代 For In
案例:__cmp__和__pow__的使用
class Person(object):
def __init__(self,num):
self.num=num
# 运算符重载
# def __add__(self, other):
# return Person(self.num + other.num)
def __pow__(self, other): #求幂运算符
return Person(self.num**other.num)
def __cmp__(self, other):
return Person(self.num==other.num)
return Person(self.num<other.num)
# def __gt__(self, other):
# return Person(self.num>other.num)
def __str__(self): #数字转成字符串
return "num =" + str(self.num)
per1=Person(8)
per2=Person(8)
print(per1**per2) #相当于print(per1__add__(per2))
print(per1.__cmp__( per2))
三,@property的使用
若直接写如 self.age=age,会直接对外暴露,起不到数据的过滤。我们可以使用__age限制访问符来进行限制
def getAge(self):
return self.__age
def setAge(self,age):
if age < 0:
age = 0
self.__age=age
per = Person(18) # 这样写直接对外暴露,不安全,没有数据的过滤
print(per.age)
per.setAge(15)
print(per.getAge())
这样能起到限制作用,但是在最后打印时会显得很麻烦。我们可以使用@property来避免
@property
def age(self):
return self.__age
@age.setter #去掉下划线.setter
def age(self,age):
if age < 0:
age = 0
self.__age=age
per = Person(18)
per.age = 100
# 相当于调用setAge
print(per.age)
# 相当于调用getAge