动态给实例添加方法
动态添加方法
from types import MethodType
c.run =MethodType(run,c)#动态传递方法,MethodType(传递的函数,与参数)
限制动态添加属性(__slots__)只允许添加内部含有的属性
示例代码
#动态给实例添加属性和方法
from types import MethodType
#空类
class Cat(object):
__slots__=('name','run')#此时只能添加name与run属性
#限制动态添加的属性
#跑
def run(self):
print(self.name+"在跑")
c=Cat()
c.name="哈哈"#添加属性
# c.run=run(c)#需要传参
#动态添加方法
c.run =MethodType(run,c)#MethodType传递的函数,与参数
c.run()
Python property() 函数
property对限制访问的使用点语法
获取@property return self.__变量名
设置@变量名.setter self.__变量名=变量名
删除@变量名.deleter del self.__变量名
class person(object):
def __init__(self,age):
self.__age = age
@property
def age(self):
#方法名为受限制变量除下划线
return self.__age
@age.setter
def age(self,age):
if age < 0:
age = 0
self.__age = age
per=person(15)
per.age=100
print(per.age)
运算符重载
# 运算符重载 class Vector(object): def __init__(self, num): self.num = num #幂运算 def __pow__(self, other): return pow(self.num,other.num) #判断(num1<num2是否成立) def __lt__(self, other): if(self.num<other.num): return True else: return False def __str__(self): print(''str()) v1=Vector(2) v2=Vector(4) print(pow(v1,v2)) print(v1<v2)
(20条消息) 浅析Python运算符重载_viclee-CSDN博客_python运算符重载的作用