Python知識(shí)分享網(wǎng) - 專業(yè)的Python學(xué)習(xí)網(wǎng)站 學(xué)Python,上Python222
Python的動(dòng)態(tài)性
匿名網(wǎng)友發(fā)布于:2023-09-12 11:11:33
(侵權(quán)舉報(bào))

Python 7天快速入門完整視頻教程https://www.bilibili.com/video/BV1o84y1Z7J1

 

Python的動(dòng)態(tài)性

 

 

Python是動(dòng)態(tài)語言,動(dòng)態(tài)語言的典型特征就是:類、對(duì)象的屬性、方法都可以動(dòng)態(tài)增加和修改。

給類動(dòng)態(tài)添加屬性和方法,語法:類名.屬性=屬性 類名.方法名=函數(shù)名

注意:動(dòng)態(tài)添加的方法,要加上self屬性

 

class Dog:
    name = None

    def say(self):
        print(f"{self.name}:汪汪")


def action_func(self):
    print(f"{self.name}:還能跑,年齡:{self.age}")


dog = Dog()
dog.name = "jack"
dog.say()
Dog.age = 11  # 給類動(dòng)態(tài)添加age屬性
Dog.action = action_func  # 給類動(dòng)態(tài)添加方法action
dog.action()

 

運(yùn)行輸出:

 

jack:汪汪
jack:還能跑,年齡:11

 

給對(duì)象動(dòng)態(tài)添加屬性和方法(其他對(duì)象作用不到)

給對(duì)象動(dòng)態(tài)添加屬性和方法,語法:對(duì)象.屬性=屬性 對(duì)象.方法名=函數(shù)名

 

class Dog:
    name = None

    def say(self):
        print(f"{self.name}:汪汪")


def action_func():
    print("還能跑")


dog = Dog()
dog.name = "jack"
dog.say()

dog.age = 11  # 給對(duì)象動(dòng)態(tài)添加age屬性
dog.action = action_func  # 給對(duì)象動(dòng)態(tài)添加方法action
dog.action()

dog2 = Dog()
dog2.name = "marry"
# print(dog2.age) # 報(bào)錯(cuò) dog2沒有age屬性
# dog2.action()  # 報(bào)錯(cuò) dog2沒有action方法

 

運(yùn)行輸出:

 

jack:汪汪
還能跑

 

 

 

轉(zhuǎn)載自: