python 动态给实例添加属性和方法并使用__slots__
from types import MethodType#创建一个空类class Person(object): __slots__ = ("name", "age", "speak")per = Person()#动态添加属性,这体现了动态语言的特点(灵活)per.name = "tom"print(per.name)#动态添加方法‘‘‘def say(self): print("my name is " + self.name)per.speak = sayper.speak(per)‘‘‘def say(self): print("my name is " + self.name)per.speak = MethodType(say, per)per.speak()#思考:如果我们想要限制实例的属性怎么办?#比如,只允许给对象添加name,age,height,weight属性#解决:定义类的时候,定义一个特殊的属性(__slots__),可以限制动态添加的属性per.height = 170print(per.height)
相关推荐
FlySky 2020-11-02
逍遥友 2020-10-26
taiyangshenniao 2020-10-05
flycony 2020-09-23
jacktangj 2020-09-18
YENCSDN 2020-09-15
lsjweiyi 2020-09-14
digwtx 2020-09-14
拾毅者 2020-09-14
zlxcsdn 2020-09-13
weiiron 2020-08-17
amazingbo 2020-08-16
郗瑞强 2020-08-16
lispython 2020-08-16
fengling 2020-08-15
xiesheng 2020-08-02
葫芦小金刚 2020-07-28
StevenSun空间 2020-07-26