修补 Python 中的类

发布于 2024-07-22 17:52:27 字数 487 浏览 4 评论 0原文

假设我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

零度℉ 2024-07-29 17:52:27

这些语句是等效的,但可能会使用 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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文