如何在Python中为实例分配属性? [英] How do I assign a property to an instance in Python?

查看:46
本文介绍了如何在Python中为实例分配属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用python,可以通过以下两种方法之一设置实例的属性:

Using python, one can set an attribute of a instance via either of the two methods below:

>>> class Foo(object):
    pass

>>> a = Foo()
>>> a.x = 1
>>> a.x
1
>>> setattr(a, 'b', 2)
>>> a.b
2

还可以通过属性装饰器分配属性.

One can also assign properties via the property decorator.

>>> class Bar(object):
    @property
    def x(self):
        return 0


>>> a = Bar()
>>> a.x
0

我的问题是,如何为实例分配属性?

My question is, how can I assign a property to an instance?

我的直觉是尝试这样的事情...

My intuition was to try something like this...

>>> class Doo(object):
    pass

>>> a = Doo()
>>> def k():
    return 0

>>> a.m = property(k)
>>> a.m
<property object at 0x0380F540>

...但是,我得到了这个奇怪的属性对象.相似的实验得出相似的结果.我的猜测是,在某些方面,属性与类的关系比实例与实例的关系更紧密,但是我不十分了解内部工作原理,无法理解这里发生的事情.

... but, I get this weird property object. Similar experimentation yielded similar results. My guess is that properties are more closely related to classes than instances in some respect, but I don't know the inner workings well enough to understand what's going on here.

推荐答案

可以在已经创建了类之后向其动态添加属性.

It is possible to dynamically add properties to a class after it's already created:

class Bar(object):
    def x(self):
        return 0

setattr(Bar, 'x', property(Bar.x))

print Bar.x
# <property object at 0x04D37270>
print Bar().x
# 0

但是,您不能仅在类上为实例设置属性.您可以使用实例来做到这一点:

However, you can't set a property on an instance, only on a class. You can use an instance to do it:

class Bar(object):
    def x(self):
        return 0

bar = Bar()

setattr(bar.__class__, 'x', property(bar.__class__.x))

print Bar.x
# <property object at 0x04D306F0>
print bar.x
# 0

请参见如何动态地向类添加属性?/a>了解更多信息.

See How to add property to a class dynamically? for more information.

这篇关于如何在Python中为实例分配属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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