动态添加属性和方法
属性
动态添加属性体现了动态语言的特点:灵活
如果创建的对象里已经创建好了属性和方法,那么这些是不可以随意修改的,但若是创建一个空对象,此时可以动态的添加
eg:
class Person:
pass#创建一个空类
per = Person()#创建一个空对象
#动态添加属性
per.name = "tom"
方法
若要动态添加方法,需提前引入
from types import MethodType
def say(self):
print("我的名字是"+self.name)
per.speak = MethodType(say,per)
per.speak()
想要限制实例的属性,如,只允许给对象添加name,age属性,那么就要在定义类的时候定义一个特殊的属性__slots__,可以限制动态实例添加属性
class Peron:
__slots__("name","age")
此时再写per.weight = 100 print(per.weight)报错,实现限制。
property
限制访问,提高安全性
运算符重载
print(1+2) 结果为3#整数1+2
print(“1”+“2”) 结果为12#字符串1+2
加法运算
class Person:
def __init__(self,num)
self.num = num
def __add__(self,other)
return Person(self.num + other.num)
per1 = Person(1)
per2 = Person(2)
print (per1+per2)
__add__函数构造表示加法运算符重载,但此刻打印出来的并非3而是地址,故需再写一个函数把字符串转变为数字
def __str__(self)
return "num="+str(self.num)
输出:num=3
关于比较运算符
该函数只有在python2中可用,而且在python2所有版本中都可用。但是在python3中该函数已经被删减掉
python3移除了cmp()函数,但提供了六个丰富的比较运算符
cmp()函数,比较运算符,如果 x < y 返回 -1, 如果 x == y 返回 0, 如果 x > y 返回 1。
import operator #首先要导入运算符模块
print(operator.gt(1,2)) #意思是greater than(大于)
print(operator.ge(1,2)) #意思是greater and equal(大于等于)
print(operator.eq(1,2)) #意思是equal(等于)
print(operator.le(1,2)) #意思是less and equal(小于等于)
print(operator.lt(1,2)) #意思是less than(小于)
输出:
False
False
False
True
True