向实例添加属性? [英] Add Properties to Instances?

查看:53
本文介绍了向实例添加属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一些只读的实例特定属性,但是

以下尝试不起作用:

I''m trying to create some read-only instance specific properties, but
the following attempt didn''t work:

class Foobar (对象):


foobar = Foobar()
foobar.x = property(fget = lambda:42)

print" foobar .x:",foobar.x


这导致以下输出而不是''42'':

foobar.x:< property对象在0x00AE57B0>


我也试过这个:foobar .__ dict __ [''x''] = property(fget = lambda:42)
class Foobar(object):
pass

foobar = Foobar()
foobar.x = property(fget=lambda: 42)

print "foobar.x:", foobar.x
Which results in the following ouput instead of ''42'':
foobar.x: <property object at 0x00AE57B0>

I also tried this: foobar.__dict__[''x''] = property(fget=lambda: 42)



但是得到了相同的行为。


谁能告诉我这种方法有什么问题(也许

正确的做法,如果有的话)?


TIA,

马丁


but get the same behavior.

Can anyone tell me what''s wrong with this approach (and perhaps the
correct way to do it, if there is one)?

TIA,
Martin

推荐答案

Martin Miller写道:
Martin Miller wrote:
我正在尝试创建一些只读的实例特定属性,但是
以下尝试不起作用:

I''m trying to create some read-only instance specific properties, but
the following attempt didn''t work:

类Foobar(对象):
传递

foobar = Foobar()
foobar.x = property(fget = lambda:42)

print" foobar.x:",foobar.x
class Foobar(object):
pass

foobar = Foobar()
foobar.x = property(fget=lambda: 42)

print "foobar.x:", foobar.x



[snip]
任何人都可以告诉我这种方法有什么问题(也许是正确的方法,如果有的话)?


[snip]
Can anyone tell me what''s wrong with this approach (and perhaps the
correct way to do it, if there is one)?




不能基于每个实例定义属性。属性必须在类级别定义
。所以你需要做类似的事情:


py> class Foobar(对象):

.... x = property(fget = lambda self:42)

....

py> ; Foobar()。x

42




py> class Foobar(对象):

....传递

....

py> Foobar.x = property(fget = lambda self:42)

py> Foobar()。x

42


如果你想在不同的实例上拥有不同的属性,你需要
需要使每个不同的实例成为不同的子类型

Foobar,例如:


py> class Foobar(对象):

....传递

....

py> foob​​ar = type(''FoobarSub'',(Foobar,),

.... dict(x = property(fget = lambda self:42)))()

py> foob​​ar.x

42

py> Foobar()。x

Traceback(最近一次调用最后一次):

文件"<交互式输入>",第1行,在?

AttributeError:''Foobar''对象没有属性''''


你认为你想要不同属性的情况是什么? b $ b为同一个班级的不同实例?


STeVe



Properties cannot be defined on a per-instance basis. Properties must
be defined at the class level. So you need to do something like:

py> class Foobar(object):
.... x = property(fget=lambda self: 42)
....
py> Foobar().x
42

or

py> class Foobar(object):
.... pass
....
py> Foobar.x = property(fget=lambda self: 42)
py> Foobar().x
42

If you want to have different properties on different instances, you''ll
need to make each of the different instances a different subtype of
Foobar, e.g.:

py> class Foobar(object):
.... pass
....
py> foobar = type(''FoobarSub'', (Foobar,),
.... dict(x=property(fget=lambda self: 42)))()
py> foobar.x
42
py> Foobar().x
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
AttributeError: ''Foobar'' object has no attribute ''x''

What''s the situation in which you think you want different properties
for different instances of the same class?

STeVe


2005年3月12日星期六09:48:42 -0800,Martin Miller写道:
On Sat, 12 Mar 2005 09:48:42 -0800, Martin Miller wrote:
我正在尝试创建一些只读的实例特定属性,但是后续尝试不起作用:
I''m trying to create some read-only instance specific properties, but the
following attempt didn''t work:




我要回应史蒂文的评论:你的情况是什么?b $ b b你认为你想要的不同同一个

类的不同实例的属性?"


另一个想法是自定义__setattr__和一些支持:


Python 2.3.5(#1,2005年3月3日,17:3 2:12)

[GCC 3.4.3(Gentoo Linux 3.4.3,ssp-3.4.3-0,pie-8.7.6.6)] on linux2

类型帮助,版权,信用和信用。或许可证或更多信息。



I''m going to echo Steven''s comment: "What''s the situation in which you
think you want different properties for different instances of the same
class?"

Another thought would be a custom __setattr__ and a bit of support:

Python 2.3.5 (#1, Mar 3 2005, 17:32:12)
[GCC 3.4.3 (Gentoo Linux 3.4.3, ssp-3.4.3-0, pie-8.7.6.6)] on linux2
Type "help", "copyright", "credits" or "license" for more information.

import sets
class ReadOnlyAttributes(object):
.... def __init__ (个体经营):

.... self .__ dict __ [''_ readOnly''] = sets.Set()

.... def addReadOnly(self,key ,价值):

.... setattr(自我,钥匙,价值)

.... self._readOnly.add(key)

.... def __setattr __(self,key,value):

.... if key in self._readOnly:

.... raise AttributeError( 不能设置属性)

.... self .__ dict __ [key] = value

.... r = ReadOnlyAttributes()
ra = 22
ra
22 ra = 23
ra
23 r.addReadOnly(" a",22)
ra
22 ra = 23
回溯(最近一次调用最后一次):

文件"< stdin>",第1行,在?

文件"< stdin> ;" ,第9行,在__setattr__

AttributeError:不能设置属性r.addReadOnly(" a",23)
Traceback(最近一次调用最后一次):

文件"< stdin>",第1行,在?

文件"< stdin>",第5行,在addReadOnly

文件"< stdin>",第9行,在__setattr__

AttributeError:无法设置属性
import sets
class ReadOnlyAttributes(object): .... def __init__(self):
.... self.__dict__[''_readOnly''] = sets.Set()
.... def addReadOnly(self, key, value):
.... setattr(self, key, value)
.... self._readOnly.add(key)
.... def __setattr__(self, key, value):
.... if key in self._readOnly:
.... raise AttributeError("can''t set attribute")
.... self.__dict__[key] = value
.... r = ReadOnlyAttributes()
r.a = 22
r.a 22 r.a = 23
r.a 23 r.addReadOnly("a", 22)
r.a 22 r.a = 23 Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 9, in __setattr__
AttributeError: can''t set attribute r.addReadOnly("a", 23) Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 5, in addReadOnly
File "<stdin>", line 9, in __setattr__
AttributeError: can''t set attribute




我不保证这完全符合要求,但我相信你可以从这里适应




另请注意严格地说,你不能做出真实的只读

属性,只有一个在程序员尝试简单方法时提醒程序员。

在纯Python对象中,总会有一种方法。这不应该如果你使用的是Python(我们都同意这里的成年人),你不要担心

,但是你还需要知道这一点。也就是说,这在

现实世界中确实有用。



I don''t guarantee this completely fits the bill but I''m sure you can adapt
it from here.

Also note that, strictly speaking, you can''t make a "true" read-only
attribute, only one that alerts a programmer if they try the simple way.
In a pure-Python object, there is always a way in. This shouldn''t worry
you if you''re using Python ("We''re all consenting adults here"), but you
should also be aware of that. That said, this is certainly useful in the
real world.


到目前为止,有几个人问过:
So far a couple of people have asked:
对于同一个班级的不同实例,您认为自己想要不同属性的情况是什么?
What''s the situation in which you think you want different properties
for different instances of the same class?




足够公平 - 这里去了:


基本上我正在做的是实现(是的,又一个;-)

''枚举''类使用一种方法一个实例

工厂函数,它返回一个预定义版本的定制版本的

泛型''_Enum''类实例。


它通过首先创建泛型类的实例和

然后添加属性(枚举器ID和

其他中的相应值)来创建它,这些特定于正在创建的枚举。这个

一切都运行得很好,但是我想通过正常的方法,使至少与ids不可变的值相关联的价值




这不是完整的功能,但如果对更多细节感兴趣,我会很高兴发布当前代码

。同时,我要到目前为止研究回复,并考虑整个问题(并设计)一个

多一点。

感谢所有回复的人,

Martin



Fair enough -- here goes:

Essentially what I''m doing is implementing (yes, yet another ;-)
''enumeration'' class using an an approach which involves an instance
factory function which returns a customized version of a predefined
generic ''_Enum'' class instance.

It does this by first creating an instance of the generic class and
then adds attributes (enumerator ids and corresponding values among
others) to it which are specific to the enumeration being created. This
all works pretty well, but I would like to make the values associated
with the ids immutable -- through normal means, at least.

It''s not feature complete, but I would be happy post the current code
if there is interest in more of the details. Meanwhile, I''m going to
study the replies so far and think about the whole issue (and design) a
little more.

Thanks to all who have replied,
Martin


这篇关于向实例添加属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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