Pythonで属性とメソッドを動的に追加する

1つは、プロパティとメソッドを動的に追加することです

#动态给实例添加方法和属性
from types import MethodType

class Person():
    pass

PersonObj = Person()
PersonObj.name = "jack"
print(PersonObj.name)

def Say(self):
    print("My name is",self.name)
PersonObj.Say = MethodType(Say,PersonObj)
PersonObj.Say()

次に、追加された属性名を制限します

"""
定义类的时候,定义一个特殊的属性,__slots__,可以限制动态添加的属性
"""
class Person2():
    __slots__ = ("name","age","school")

PersonObj2 = Person2()
PersonObj2.name = "Lucy"
#PersonObj2.weight = "180" 代码报错

おすすめ

転載: blog.csdn.net/zhuan_long/article/details/110387398