Python動態添加屬性和方法

動態添加屬性,就是這個屬性不是在類定義的時候添加的,而是在程序運行過程中添加的,動態添加屬性有兩種方法,第一個是直接通過對象名.屬性名,第二個是通過setattr添加:
1、第一種:使用對象.屬性名添加:

p.ageb= 18

2、第二種,使用setattr函數添加:

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

p = Person('lyc')
p.age = 18
if not hasattr(p, ’sex’):
    setattr(p, 'sex', 'male')
print(p.sex)

· 動態添加方法
動態添加實例方法:
動態添加方法,意思是方法不是在類定義的時候添加的。而是創建完這個對象後,在運行的時候添加的。如果想要在運行的時候添加方法,這時候就應該使用到types.MethodType這個方法了,示例:

import types
class Person:
    def __init__(self, name):
        self.name = name

def run(self):
    print('%s run func' % self.name)

p1 = Person('lyc')
p1.run = types.MethodType(run, p1) #這裏p1爲run方法的參數, 即self
p1.run()

動態添加類方法:
添加類方法,是把這個方法添加給類。因此添加類方法的時候不是給對象添加,而是給類添加。並且添加類方法的時候不需要使用types.MethodType,直接將這個函數賦值給類就可以了,但是需要使用classmethod裝飾器將這個方法設置爲一個類方法。

@classmethod
def show(cls):
    print('這是類方法')

Person.show = show
Person.show()

動態添加靜態方法:

@classmethod
def show(cls):
    print('這是類方法')

Person.show = show
Person.show()
·  動態刪除屬性和方法
1、del 對象.屬性名
print(p1.name)
del p1.name
print(p1.name)
2、delattr(對象,“屬性名”)
print(p1.name)
del p1.name
print(p1.name)

魔術方法__slots__:
使用__slots__來指定類中允許添加的屬性,如下只能添加 name,和age這兩個屬性

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

p2 = Person('lyc')
p2.age = 18
print(p2.age)
#下邊代碼會報錯
p2.country = 'zh'
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章