添加属性和方法:
class Cat(object):
def __init__(self, name):
self.name = name
# 创建2个Cat,分别为cat1,cat2
cat1 = Cat('Tom') # 名字叫Tom的猫
print(cat1.name)
cat2 = Cat('加菲') # 加菲猫
print(cat2.name)
def run(self): # Cat类外定义一个奔跑的方法
print('%s run' % (self.name))
Cat.run = run # 实例化对象
Cat.run(cat1) # 输出 Tom run
Cat.run(cat2) # 输出 加菲 run
结果:
Tom
加菲
Tom run
加菲 run
运算符重构:
class Next(object):
def __init__(self, data=1):
self.data = data
def __iter__(self):
return self
def __next__(self):
if self.data > 5:
raise StopIteration
else:
self.data += 1
return self.data
n = Next(3)
i = iter(n)
print(i)
<__main__.Next object at 0x0000022DEF3F0FD0>
pow重构
class Score(object):
def __init__(self, one):
self.one = one
def __pow__(self, power, modulo=None):
return self.one ** power.one
Score1 = Score(3)
Score2 = Score(2)
print(Score1 ** Score2)
9