动态添加类的属性和方法
from types import MethodType
class Person(object):
pass
per = Person()
per.name = "tom"
print(per.name)
def say(self):
print("my name is " + self.name)
per.speak = MethodType(say, per)
per.speak()
'''
per.speak = say 方法二,略微简陋
per.speak(per)
'''
class Kong(object):
__slots__ = ("name", "age", "speak")
kong = Kong()
kong.name = "吃"
---执行结果-------------------------------------------------------
tom
my name is tom
进程已结束,退出代码为 0
@property装饰器
class Person(object):
def __init__(self, age):
self.__age = age
'''
def setAge(self, age):
if age > 0:
self.__age = age
else:
self.__age = 0
def getAge(self):
return self.__age
'''
@property
def age(self):
return self.__age
@age.setter
def age(self, age):
if age > 0:
self.__age = age
else:
self.__age = 0
per = Person(18)
per.age = -13
print(per.age)
---执行结果----------------------------------------
0
进程已结束,退出代码为 0
运算符重载
print(1 + 2)
print("1" + "2")
class Person (object):
def __init__(self, num):
self.num = num
def __add__(self, other):
return Person(self.num + other.num)
def __str__(self):
return "num = " + str(self.num)
per1 = Person(1)
per2 = Person(1)
print(per1 + per2)
print(per1)
print(per2)
---执行结果-----------------------------------------------
3
12
num = 2
num = 1
num = 1
进程已结束,退出代码为 0
练习
- 动态给类添加方法,具体是对猫的类中没有设置奔跑的方法,在类外添加这个方法,并打印显示
from types import MethodType
class Cat(object):
def __init__(self, name):
self.name = name
def run(self):
print(self.name + "在奔跑")
tom = Cat("Tom")
tom.run = MethodType(run, tom)
tom.run()
---执行结果-------------------------------------
Tom在奔跑
进程已结束,退出代码为 0
- 在类中对__pow__、__cmp__进行运算符重载,主要对的两个成绩进行平方运算、比较两个成绩
import operator
class Score(object):
def __init__(self, name, num):
self.name = name
self.num = num
def __pow__(self, power, modulo=None):
return Score(self.name, pow(self.num, power))
def __lt__(self, other):
if self.num > other.num:
return self.name + "的成绩更高"
else:
return other.name + "的成绩更高"
def __str__(self):
return self.name + "的成绩是" + str(self.num)
sco1 = Score("张三", 59)
sco2 = Score("老罗", 61)
print(pow(sco1, 2))
print(operator.lt(sco1, sco2))
---执行结果-------------------------------------
张三的成绩是3481
老罗的成绩更高
进程已结束,退出代码为 0
|