python动态添加属性和方法

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

p1 = Person('ff', '28')
print(p1.name, p1.age)

# 给实例对象动态添加sex属性
p1.sex = 'female'

print(p1.sex)

# 给类动态添加属性
Person.height = None
print(Person.height)
p1.height = '155'
print(p1.height)


# 动态定义一个方法
def run(self, speed):
    print('run with %d speed' % speed)

# 给实例绑定方法
import types
p1.run = types.MethodType(run, p1)
p1.run(30)

# Person.run = run # 运行错误 

# Person.run(4)

@classmethod
def run2(a, speed):
    print('run with %d m/s' % speed)
# 给类动态绑定方法
Person.run2 = run2       # 给类绑定的方法, 需加修饰器 @classmethod, 标定其为类方法,可被类添加

Person.run2(4)

p1.run2(5)              # 类的实例对象也可调用类动态添加的方法

@staticmethod
def eat():
    print('eat---')

Person.eat = eat        # 类可添加静态方法, 定义静态方法时,需加修饰器@staticmethod

Person.eat()

p1.eat()                # 实例对象同样可调用类动态添加的静态方法


del p1.name             # del 删除属性
delattr(p1, 'sex')
print(p1.name, p1.sex)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58

运行结果:

ff 28
female
None
155
run with 30 speed
run with 4 m/s
run with 5 m/s
eat---
eat---
Traceback (most recent call last):
  File "/home/python/Desktop/test/12_动态语言.py", line 57, in <module>
    print(p1.name, p1.sex)
AttributeError: 'Person' object has no attribute 'name'

---------------------
作者:fanfen88
来源:CSDN
原文:https://blog.csdn.net/fanfen88/article/details/78309898
版权声明:本文为博主原创文章,转载请附上博文链接!

posted @ 2019-07-20 09:16  天涯海角路  阅读(99)  评论(0)    收藏  举报