修补 Python 中的类
假设我有一个 Python 类,我想向其中添加额外的属性。
之间有什么区别吗
import path.MyClass
MyClass.foo = bar
和 使用类似 :
import path.MyClass
setattr(MyClass, 'foo', bar)
?
如果不是,为什么人们似乎会做第二个而不是第一个? (例如,这里http://concisionandconcinnity.blogspot。 com/2008/10/chaining-monkey-patches-in-python.html )
Suppose I have a Python class that I want to add an extra property to.
Is there any difference between
import path.MyClass
MyClass.foo = bar
and using something like :
import path.MyClass
setattr(MyClass, 'foo', bar)
?
If not, why do people seem to do the second rather than the first? (Eg. here http://concisionandconcinnity.blogspot.com/2008/10/chaining-monkey-patches-in-python.html )
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这些语句是等效的,但可能会使用 setattr,因为它是两者中最动态的选择(使用 setattr,您可以使用变量作为属性名称。)
请参阅:http://docs.python.org/library/functions.html#setattr
The statements are equivalent, but setattr might be used because it's the most dynamic choice of the two (with setattr you can use a variable for the attribute name.)
See: http://docs.python.org/library/functions.html#setattr