动态给实例添加属性和方法
from types import MethodType#导入模块
class Cat(object):#定义一个类
def eat(self):#定义一个方法
print("吃")
cat1=Cat()#实例化对象
def run(self):#新定义一个类
print("跑")
cat1.run =MethodType(run,cat1)#将类加入
cat1.run()
运算符重载
Python同样支持运算符重载,我们可以对类的专有方法进行重载,实例如下:
class Vector:
def __init__(self, a, b):
self.a = a
self.b = b
def __str__(self):
return 'Vector (%d, %d)' % (self.a, self.b)
def __add__(self,other):
return Vector(self.a + other.a, self.b + other.b)
v1 = Vector(2,10)
v2 = Vector(5,-2)
print (v1 + v2)
运行结果
Vector(7,8)
pow和比较方法重写
import operator
class car(object):#定义一个类
def __init__(self,num):#将成绩分别传给参数
self.num=num
def __pow__(self, power, modulo=None):#pow方法重写
return pow(self.num,2)
G1=car(11)#实例化对象
G2=car(22)
G3=car(22)
G4=car(10)
print(operator.lt('G1','G4'))#比较方法重写
#operator.lt()函数是运营商模块的库函数,
# 它被用于在两个值并返回true执行“小于操作”
# 如果第一值小于所述第二值,假 ,否则。为真
print(pow(G1,2))#输出结果
print(pow(G2,2))
print(pow(G3,2))
print(pow(G4,2))
因为cmp在python3中被取消,所以比较使用的是operator.lt