Dynamically add attributes and methods in Python

One, dynamically add properties and methods

#动态给实例添加方法和属性
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()

Second, restrict the added attribute name

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

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

Guess you like

Origin blog.csdn.net/zhuan_long/article/details/110387398