Python---动态属性方法的添加和限制添加属性

在没有定义一个属性的时候,我们可以动态的定义一个属性或者方法。

动态定义属性

from types import MethodType
class  Person:
    pass

if __name__ == '__main__':
    p = Person()
    p.name = "laobi"
    print(p.name)






F:\学习代码\Python代码\venv\Scripts\python.exe F:/学习代码/Python代码/day5/动态添加属性.py
laobi

Process finished with exit code 0

有些情况没有在定义类是添加它的属性或者方法(比如,我们使用第三方函数库的时候)。但可以通过动态的方法,在程序执行的过程中添加。

动态定义方法

from types import MethodType
class  Person:
    pass

def tell(self):
    print("my name is %s"%(self.name))

if __name__ == '__main__':
    p = Person()
    p.name = "laobi"
    print(p.name)
    p.speak = MethodType(tell,p)
    #将tell方法绑定到p上
    p.speak()





F:\学习代码\Python代码\venv\Scripts\python.exe F:/学习代码/Python代码/day5/动态添加属性.py
laobi
my name is laobi

Process finished with exit code 0

__slots__限制动态添加属性或方法

class Person:
    __slots__ = ("name","age")
    def __init__(self,name,age):
        self.name = name
        self.age = age

if __name__ == '__main__':
    p = Person("小红",20)
    print(p.name)
    print(p.age)

    # p.tell = "20000"
    # print(p.tell)




F:\学习代码\Python代码\venv\Scripts\python.exe F:/学习代码/Python代码/day5/限制添加属性.py
小红
20

Process finished with exit code 0

猜你喜欢

转载自blog.csdn.net/qq_41112887/article/details/88748962