可以设置Python对象的任何属性 [英] Can set any property of Python object

查看:115
本文介绍了可以设置Python对象的任何属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,此代码是Python:

For example, this code is Python:

a = object()
a.b = 3

throws AttributeError:'object'object没有属性'b'

但是,这段代码:

class c(object): pass
a = c()
a.b = 3

正好。为什么我可以分配属性b,当类x没有该属性?如何使我的类只有属性定义?

is just fine. Why can I assign property b, when class x does not have that property? How can I make my classes have only properties defined?

推荐答案

对象 type是一个用C语言编写的内置类,不允许您向其中添加属性。

The object type is a built-in class written in C and doesn't let you add attributes to it. It has been expressly coded to prevent it.

在你自己的类中获得相同行为的最简单方法是使用 __ slots __ 属性来定义要支持的确切属性的列表。 Python将为这些属性保留空间,不允许任何其他属性。

The easiest way to get the same behavior in your own classes is to use the __slots__ attribute to define a list of the exact attributes you want to support. Python will reserve space for just those attributes and not allow any others.

class c(object):
    __slots__ = "foo", "bar", "baz"

a = c()

a.foo = 3  # works
a.b   = 3  # AttributeError

当然,这种方法有一些注意事项:你不能pickle这样的对象,对象有一个 __ dict __ 属性将打破。 更多的Pythonic方式将使用自定义 __ setattr __(),如另一个海报所示。当然,有很多方法,没有办法设置 __ slots __ (除了子类和添加您的属性到子类)。

Of course, there are some caveats with this approach: you can't pickle such objects, and code that expects every object to have a __dict__ attribute will break. A "more Pythonic" way would be to use a custom __setattr__() as shown by another poster. Of course there are plenty of ways around that, and no way around setting __slots__ (aside from subclassing and adding your attributes to the subclass).

一般来说,这不是你真正想在Python中做的事情。如果你的类的用户想要在类的实例上存储一些额外的属性,没有理由不让他们,而事实上,你可能想要的很多原因。

In general, this is not something you should actually want to do in Python. If the user of your class wants to store some extra attributes on instances of the class, there's no reason not to let them, and in fact a lot of reasons why you might want to.

这篇关于可以设置Python对象的任何属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆