自动访问成员var dict元素? [英] automatic accessors to a member var dict elements?

查看:54
本文介绍了自动访问成员var dict元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有以下课程:


class MyClass:

def __init __(self):

m_dict = { }

m_dict [''one''] = 1

m_dict [''two''] = 2

m_dict [''三''] = 3


无论如何都要生成dict元素的自动访问器吗?

例如,我可以说:


obj = MyClass()

obj.one#returns obj.my_dict [''one'']

obj.one =' '赢''#与obj.my_dict相同[''one''] =''赢''


通过自动,我的意思是所以我不必写出来每个方法都是手工和

也是动态的,这意味着如果m_dict在运行时发生变化,访问者将自动更新以反映变化。


感谢您的帮助。

解决方案

Christopher J. Bottaro写道:

如果我有以下课程:

类MyClass:
def __init __(self):
m_dict = {}
m_dict [''one''] = 1
m_dict [' 'two''] = 2
m_dict [''three''] = 3


首先,如果你想要,你需要保留该dict的副本

能用它做任何事情。你在__init __()里面创建m_dict作为一个本地的

变量,当__init __()

结束时,它超出范围,然后被垃圾收集。为了让它留在身边,存储它作为''self'的属性
-


self.m_dict = {}

self.m_dict [''one''] = 1

self.m_dict [''two''] = 2


等等on。

无论如何都要生成dict元素的自动访问器吗?
例如,我可以说:

obj = MyClass()
obj.one #wats obj.my_dict [''one'']
obj.one =''won''#与obj.my_dict相同[''one''] =''won''




如果您希望能够访问这些项目,就好像它们是您的类实例的纯粹

属性一样,是你有什么理由不把它们作为属性创建吗?


class MyClass:

def __init ___(self ):

self.one = 1


obj = MyClass()

obj.one# - > 1

obj.one =''won''


如果你确实需要单独维护字典,那么你可以使用

__getattr __()和__setattr __()将不存在的

属性的访问重定向到包含的dict中的操作,类似这样的事情

(未经测试):


class MyClass(object):#确保一个新式的类

def __init __(自我):

self.m_dict = {''一个'':1,''两个'':2,''三'':3}

def __getattr __(self,attr):

value = self。 m_dict.get(attr,None)

如果值为None:

raise AttributeError(attr)

返回值

def __setattr __(self,attr,value):

self.m_dict [attr] = value


我正在使用新式课程利用

属性查找的改进。对于这个类,__ getattr __()/ __ setattr __()只有在通过正常属性解析找不到attr时才会调用


规则。


我在这里做的事情的一个问题是,如果你将一个

dict项设置为None值,该对象将引发一个AttributeError

尝试访问该项目时。这真的应该使用更安全的

哨兵价值。 (检查clpy中最近的一个帖子是关于

哨兵值和object()的使用情况。)


有可能使用你似乎想要的机制

(自动生成单独的get / set方法,将它们附加到

实例,从getter / setter创建一个新属性),但是

会涉及更多的复杂性和魔法,并且会很少(如果有的话)获得



Jeff Shannon

技术员/程序员

Credit International


2004年10月14日星期四17:56:09 -0700,Jeff Shannon< je ** @ ccvcorp.com>写道:

[...]


如果你确实需要单独维护dict,那么你可以使用
__getattr __()和__setattr __()将不存在的
属性的访问重定向到包含的dict中的操作,类似这样的事情
(未经测试):

类MyClass(对象):#确保新的 - 风格类
def __init __(自我):
self.m_dict = {''one'':1,''two'':2,''three'':3}
def __getattr __(self,attr):
try:return self.m_dict [attr]
除了KeyError之外的
:raise AttributeError(attr)

value = self.m_dict。 get(attr,None)
如果值为None:
引发AttributeError(attr)
返回值
def __setattr __(self,attr,value):
self。 m_dict [attr] = value

我正在使用一种新式的类来利用
属性查找的改进。对于这个类,如果没有通过正常的属性解析规则找到attr,则只会调用__getattr __()/ __ setattr __()。

这个方法有一个问题我在这里做的是,如果你将一个
dict项设置为None值,那么当试图访问该项时,该对象将引发一个AttributeError
。这真的应该使用更安全的哨兵价值。 (检查clpy中最近的一个关于
sentinel值和object()的使用的线程。)



为什么不(未经测试)避免默认的哨兵和只需翻译

a关键错误,如上所述属性错误?


问候,

Bengt Richter


Christopher J. Bottaro< cj ******* @ alumni.cs.utexas.edu>写道:

如果我有以下课程:

类MyClass:
def __init __(self):
m_dict = {}
m_dict [''one''] = 1
m_dict [''two''] = 2
m_dict [''three''] = 3

无论如何都有生成dict元素的自动访问器?
例如,我可以说:

obj = MyClass()
obj.one#returns obj.my_dict [''一个'']
obj.one =''赢''#与obj.my_dict相同[''one''] =''赢''

通过自动,我的意思是如此我不必手动写出每个方法,也不需要动态,这意味着如果m_dict在运行时发生变化,访问者将自动更新以反映变化。




这是一种旧式的做法。我认为新风格的课程可能会有更好的方式,但是我不能加快速度!


注意设置m_dict as self .__ dict __ [" m_dict"]而不是

self.m_dict否则__setattr__会递归!如果你愿意的话,你可以在__setattr__中放一个

的特殊情况。


class MyClass:

def __init __(self):

self .__ dict __ [" m_dict"] = {}

self.m_dict [''one''] = 1

self.m_dict [''two''] = 2

self.m_dict [''three''] = 3

def __getattr __(自我,姓名):

返回self.m_dict [name]

def __setattr __(self,name,value):

self.m_dict [name] = value

obj = MyClass()
print obj.one
1 obj.one =''won''
print obj.one



won


-

Nick Craig-Wood< ni ** @ craig-wood.com> - http://www.craig-wood.com/nick


If I have the following class:

class MyClass:
def __init__(self):
m_dict = {}
m_dict[''one''] = 1
m_dict[''two''] = 2
m_dict[''three''] = 3

Is there anyway to generate automatic accessors to the elements of the dict?
For example, so I could say:

obj = MyClass()
obj.one # returns obj.my_dict[''one'']
obj.one = ''won'' # same as obj.my_dict[''one''] = ''won''

By automatic, I mean so I don''t have to write out each method by hand and
also dynamic, meaning if m_dict changes during runtime, the accessors are
automatically updated to reflect the change.

Thanks for the help.

解决方案

Christopher J. Bottaro wrote:

If I have the following class:

class MyClass:
def __init__(self):
m_dict = {}
m_dict[''one''] = 1
m_dict[''two''] = 2
m_dict[''three''] = 3

First of all, you need to hold onto a copy of that dict if you want to
be able to do anything with it. You''re creating m_dict as a local
variable inside of __init__(), which goes out of scope when __init__()
ends, and is then garbage-collected. To get it to stay around, store it
as an attribute of ''self'' --

self.m_dict = {}
self.m_dict[''one''] = 1
self.m_dict[''two''] = 2

and so on.
Is there anyway to generate automatic accessors to the elements of the dict?
For example, so I could say:

obj = MyClass()
obj.one # returns obj.my_dict[''one'']
obj.one = ''won'' # same as obj.my_dict[''one''] = ''won''



If you want to be able to access these items as if they were plain
attributes of your class instance, is there any reason why you''re not
just creating them as attributes?

class MyClass:
def __init___(self):
self.one = 1

obj = MyClass()
obj.one # --> 1
obj.one = ''won''

If you really do need to maintain the dict separately, then you can use
__getattr__() and __setattr__() to redirect accesses of nonexistent
attributes into operations on your contained dict, something like this
(untested):

class MyClass(object): # ensure a new-style class
def __init__(self):
self.m_dict = {''one'':1, ''two'':2, ''three'':3}
def __getattr__(self, attr):
value = self.m_dict.get(attr, None)
if value is None:
raise AttributeError(attr)
return value
def __setattr__(self, attr, value):
self.m_dict[attr] = value

I''m using a new-style class to take advantage of improvements in
attribute lookup. For this class, __getattr__()/__setattr__() will only
be called if attr isn''t found through the normal attribute resolution
rules.

One problem with the way I''m doing things here is that, if you set a
dict item to a value of None, the object will raise an AttributeError
when trying to access that item. This really ought to use a safer
sentinel value. (Check for a recent thread here in c.l.py about
sentinel values and the use of object() as one.)

It might be possible to use the mechanism you seem to want
(automatically generating individual get/set methods, attaching them to
the instance, creating a new property from the getter/setter), but that
would involve significantly more complexity and magic, and would gain
you very little (if anything).

Jeff Shannon
Technician/Programmer
Credit International


On Thu, 14 Oct 2004 17:56:09 -0700, Jeff Shannon <je**@ccvcorp.com> wrote:
[...]


If you really do need to maintain the dict separately, then you can use
__getattr__() and __setattr__() to redirect accesses of nonexistent
attributes into operations on your contained dict, something like this
(untested):

class MyClass(object): # ensure a new-style class
def __init__(self):
self.m_dict = {''one'':1, ''two'':2, ''three'':3}
def __getattr__(self, attr): try: return self.m_dict[attr]
except KeyError: raise AttributeError(attr)
value = self.m_dict.get(attr, None)
if value is None:
raise AttributeError(attr)
return value
def __setattr__(self, attr, value):
self.m_dict[attr] = value

I''m using a new-style class to take advantage of improvements in
attribute lookup. For this class, __getattr__()/__setattr__() will only
be called if attr isn''t found through the normal attribute resolution
rules.

One problem with the way I''m doing things here is that, if you set a
dict item to a value of None, the object will raise an AttributeError
when trying to access that item. This really ought to use a safer
sentinel value. (Check for a recent thread here in c.l.py about
sentinel values and the use of object() as one.)


Why not (untested) avoid the default sentinel and just translate
a key error to an attribute error as above?

Regards,
Bengt Richter


Christopher J. Bottaro <cj*******@alumni.cs.utexas.edu> wrote:

If I have the following class:

class MyClass:
def __init__(self):
m_dict = {}
m_dict[''one''] = 1
m_dict[''two''] = 2
m_dict[''three''] = 3

Is there anyway to generate automatic accessors to the elements of the dict?
For example, so I could say:

obj = MyClass()
obj.one # returns obj.my_dict[''one'']
obj.one = ''won'' # same as obj.my_dict[''one''] = ''won''

By automatic, I mean so I don''t have to write out each method by hand and
also dynamic, meaning if m_dict changes during runtime, the accessors are
automatically updated to reflect the change.



Here is an old style class way of doing it. I think there might be a
better way with new style classes but I''m not up to speed on them!

Note care taken to set m_dict as self.__dict__["m_dict"] rather than
self.m_dict otherwise the __setattr__ will recurse! You can put a
special case in __setattr__ if you prefer.

class MyClass:
def __init__(self):
self.__dict__["m_dict"] = {}
self.m_dict[''one''] = 1
self.m_dict[''two''] = 2
self.m_dict[''three''] = 3
def __getattr__(self, name):
return self.m_dict[name]
def __setattr__(self, name, value):
self.m_dict[name] = value

obj = MyClass()
print obj.one 1 obj.one = ''won''
print obj.one


won

--
Nick Craig-Wood <ni**@craig-wood.com> -- http://www.craig-wood.com/nick


这篇关于自动访问成员var dict元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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