Python setattr()

def setattr(x, y, v): # real signature unknown; restored from __doc__
"""
Sets the named attribute on the given object to the specified value.

setattr(x, 'y', v) is equivalent to ``x.y = v''
"""
pass
class Person(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def walk(self):
        print("%s is walking..." % self.name)


def talk1(aaaa):
    print('%s is talking...1' % aaaa.name)


def talk2(self):
    print('%s is talking...2' % self.name)


if __name__ == '__main__':
    p1 = Person('jack', 18)
    p1.walk()
    setattr(Person, 'speak1', talk1)
    p1.speak1()
    setattr(Person, 'speak2', talk2)
    p1.speak2()

    p2 = Person('mike', 19)
    p2.speak1()

jack is walking...
jack is talking...1
jack is talking...2
mike is talking...1

这段代码通过内置setattr函数给Person类动态地增加了实例方法speak1和speak2 ,实例化了p1和p2实例,

在setattr函数执行之后,p1,p2就都能够通过对象加点加方法(p1.speak1, p2.speak1)的方式查找到新增的speak1,speak2方法了。

posted @ 2022-12-03 23:55  fangpinz  阅读(36)  评论(0编辑  收藏  举报