gpt4 book ai didi

Python:在运行时更改方法和属性

转载 作者:IT老高 更新时间:2023-10-28 21:35:53 26 4
gpt4 key购买 nike

我希望在 Python 中创建一个可以添加和删除属性和方法的类。我怎样才能做到这一点?

哦,请不要问为什么。

最佳答案

这个例子展示了将方法添加到类和实例之间的区别。

>>> class Dog():
... def __init__(self, name):
... self.name = name
...
>>> skip = Dog('Skip')
>>> spot = Dog('Spot')
>>> def talk(self):
... print 'Hi, my name is ' + self.name
...
>>> Dog.talk = talk # add method to class
>>> skip.talk()
Hi, my name is Skip
>>> spot.talk()
Hi, my name is Spot
>>> del Dog.talk # remove method from class
>>> skip.talk() # won't work anymore
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: Dog instance has no attribute 'talk'
>>> import types
>>> f = types.MethodType(talk, skip, Dog)
>>> skip.talk = f # add method to specific instance
>>> skip.talk()
Hi, my name is Skip
>>> spot.talk() # won't work, since we only modified skip
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: Dog instance has no attribute 'talk'

关于Python:在运行时更改方法和属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/962962/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com