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. 12 2016
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__(sel f, attr):
value = self.m_dict.get (attr, None)
if value is None:
raise AttributeError( attr)
return value
def __setattr__(sel f, 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.c om> 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__(sel f, 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__(sel f, 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*******@alum ni.cs.utexas.ed u> 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__(sel f, name):
return self.m_dict[name]
def __setattr__(sel f, 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
Jeff Shannon <je**@ccvcorp.c om> wrote: class MyClass(object) : # ensure a new-style class def __init__(self): self.m_dict = {'one':1, 'two':2, 'three':3} def __getattr__(sel f, attr): value = self.m_dict.get (attr, None) if value is None: raise AttributeError( attr) return value def __setattr__(sel f, 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.
It doesn't! class MyClass(object) : # ensure a new-style class
.... def __init__(self):
.... self.m_dict = {'one':1, 'two':2, 'three':3}
.... def __getattr__(sel f, attr):
.... value = self.m_dict.get (attr, None)
.... if value is None:
.... raise AttributeError( attr)
.... return value
.... def __setattr__(sel f, attr, value):
.... self.m_dict[attr] = value
.... obj = MyClass()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 3, in __init__
File "<stdin>", line 10, in __setattr__
File "<stdin>", line 5, in __getattr__
File "<stdin>", line 5, in __getattr__
File "<stdin>", line 5, in __getattr__
File "<stdin>", line 5, in __getattr__
File "<stdin>", line 5, in __getattr__
[snip]
File "<stdin>", line 5, in __getattr__
File "<stdin>", line 5, in __getattr__
RuntimeError: maximum recursion depth exceeded
I know there is something different about new style classes in this
area, but thats not it!
--
Nick Craig-Wood <ni**@craig-wood.com> -- http://www.craig-wood.com/nick
On 15 Oct 2004 08:30:02 GMT, Nick Craig-Wood <ni**@craig-wood.com> wrote: Jeff Shannon <je**@ccvcorp.c om> wrote: class MyClass(object) : # ensure a new-style class def __init__(self): self.m_dict = {'one':1, 'two':2, 'three':3} def __getattr__(sel f, attr): value = self.m_dict.get (attr, None) if value is None: raise AttributeError( attr) return value def __setattr__(sel f, 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. It doesn't!
Oops, I missed that too, as I was focusing on the if-value-is-None logic, class MyClass(object) : # ensure a new-style class... def __init__(self): ... self.m_dict = {'one':1, 'two':2, 'three':3} ... def __getattr__(sel f, attr): ... value = self.m_dict.get (attr, None) ... if value is None: ... raise AttributeError( attr) ... return value ... def __setattr__(sel f, attr, value): ... self.m_dict[attr] = value
Maybe: class MyClass(object) : # ensure a new-style class
... def __init__(self):
... object.__setatt r__(self, 'm_dict', {'one':1, 'two':2, 'three':3})
... def __getattr__(sel f, attr):
... if attr == 'm_dict': return object.__getatt ribute__(self, attr)
... try: return self.m_dict[attr]
... except KeyError: raise AttributeError( attr)
... def __setattr__(sel f, attr, value):
... self.m_dict[attr] = value
... mc = MyClass() mc.two
2 mc.three
3 mc.four
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 7, in __getattr__
AttributeError: four mc.four = 4 mc.four
4 mc.m_dict
{'four': 4, 'three': 3, 'two': 2, 'one': 1}
... obj = MyClass()
Traceback (most recent call last): File "<stdin>", line 1, in ? File "<stdin>", line 3, in __init__ File "<stdin>", line 10, in __setattr__ File "<stdin>", line 5, in __getattr__ File "<stdin>", line 5, in __getattr__ File "<stdin>", line 5, in __getattr__ File "<stdin>", line 5, in __getattr__ File "<stdin>", line 5, in __getattr__ [snip] File "<stdin>", line 5, in __getattr__ File "<stdin>", line 5, in __getattr__ RuntimeError : maximum recursion depth exceeded
I know there is something different about new style classes in this area, but thats not it!
You can make self.m_dict raise an attribute error too, but then you can't
write your methods with self.m_dict, since that will trigger recursion.
object.__getatt ribute__(self, 'm_dict') instead.
Bottom line, though: Why use self.m_dict when you get self.__dict__ for free,
along with attribute access? I.e., self.x is effectively self.__dict__['x']
IOW, self.__dict__ works like you went to all that trouble to make self.m_dict work,
unless your class defines class variables or properties that you want to shadow under
all circumstances.
Regards,
Bengt Richter
Nick Craig-Wood wrote: class MyClass(object) : # ensure a new-style class
... def __init__(self): ... self.m_dict = {'one':1, 'two':2, 'three':3} ... def __getattr__(sel f, attr): ... value = self.m_dict.get (attr, None) ... if value is None: ... raise AttributeError( attr) ... return value ... def __setattr__(sel f, attr, value): ... self.m_dict[attr] = value ...
obj = MyClass()
Traceback (most recent call last): File "<stdin>", line 1, in ? File "<stdin>", line 3, in __init__ File "<stdin>", line 10, in __setattr__ File "<stdin>", line 5, in __getattr__ File "<stdin>", line 5, in __getattr__ File "<stdin>", line 5, in __getattr__ File "<stdin>", line 5, in __getattr__ File "<stdin>", line 5, in __getattr__ [snip] File "<stdin>", line 5, in __getattr__ File "<stdin>", line 5, in __getattr__ RuntimeError : maximum recursion depth exceeded
I know there is something different about new style classes in this area, but thats not it!
Hmmm... Actually, I think that the problem here is that during
__init__(), we're trying to set the attribute m_dict, which doesn't
exist yet, so it tries to look in self.m_dict to find it...
Modifying __init__() so to use self.__dict__['m_dict'] instead of
self.m_dict will likely fix this. (But I still haven't tested it...)
Jeff Shannon
Technician/Programmer
Credit International
Bengt Richter wrote: On Thu, 14 Oct 2004 17:56:09 -0700, Jeff Shannon <je**@ccvcorp.c om> wrote: [...]
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?
Good point -- that makes this safer, cleaner, and more Pythonic. :)
Jeff Shannon
Technician/Programmer
Credit International
Jeff Shannon wrote: Nick Craig-Wood wrote:
I know there is something different about new style classes in this area, but thats not it!
Hmmm... Actually, I think that the problem here is that during __init__(), we're trying to set the attribute m_dict, which doesn't exist yet, so it tries to look in self.m_dict to find it...
Modifying __init__() so to use self.__dict__['m_dict'] instead of self.m_dict will likely fix this. (But I still haven't tested it...)
And, because I'm slacking off on my real work: class MyClass(object) :
.... def __init__(self):
.... self.__dict__['m_dict'] = {'one':1, 'two':2, 'three':3}
.... def __getattr__(sel f, attr):
.... try:
.... value = self.m_dict[attr]
.... except KeyError:
.... raise AttributeError( attr)
.... return value
.... def __setattr__(sel f, attr, value):
.... self.m_dict[attr] = value
.... obj = MyClass() obj.one
1 obj.two
2 obj.one = 'won' obj.one
'won' obj.four = 4 obj.m_dict
{'four': 4, 'three': 3, 'two': 2, 'one': 'won'} obj.five
Traceback (most recent call last):
File "<interacti ve input>", line 1, in ?
File "<interacti ve input>", line 8, in __getattr__
AttributeError: five
Hm, that error message is a bit weak. If we replace the 'raise
AttributeError( attr)' with '''raise AttributeError( "%s instance has no
attribute '%s'" % (self.__class__ .__name__, attr))''', we'll get an
error message that's much more in line with a 'normal' AttributeError.
obj.five
Traceback (most recent call last):
File "<interacti ve input>", line 1, in ?
File "<interacti ve input>", line 8, in __getattr__
AttributeError: MyClass instance has no attribute 'five'
Jeff Shannon
Technician/Programmer
Credit International
Jeff Shannon <je**@ccvcorp.c om> wrote:
... __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__(sel f, attr): value = self.m_dict.get (attr, None) if value is None: raise AttributeError( attr) return value def __setattr__(sel f, 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
Yes for __getattr__, but no for __setattr__ -- in both cases, just like
in classic classes. When in __init__ you try to set attr m_dict (and in
this case it wouldn't even make much sense to say it's "found through
the normal attribute resolution" -- it's not there yet at that time, so
it couldn't be found), this invokes __setattr__, which goes boom
(because m_dict ain't set yet). If you needed that __setattr__, your
__init__ should assign self.__dict__['m_dict'] instead. But the OP
didn't ask for that __setattr__ anyway, so I'd remove it instead.
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.)
A better solution than a sentinel, in this case:
def __getattr__(sel f, attr):
try: return self.m_dict[attr]
except KeyError: raise AttributeError, attr
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).
Complete agreement here -- __getattr__ is clearly the way to go for this
specific requirement.
Alex This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: svilen |
last post by:
hello again.
i'm now into using python instead of another language(s) for
describing structures of data, including names, structure,
type-checks, conversions, value-validations, metadata etc. And i have
things to offer, and to request.
And a lot of ideas, but who needs them....
here's an example (from type_struct.py):
|
by: Generic Usenet Account |
last post by:
A lot has been said in this newsgroup regarding the "evil" set/get
accessor methods. Arthur Riel, (of Vanguard Training), in his class,
"Heuristis for O-O Analysis & Design", says that there is almost never
an excuse for accessor methods. Personally, I do not go that far. I
do feel that they serve a useful purpose (albeit in a limited manner).
Personally I prefer dropping the "set" and "get" prefixes from the
method names altogether. ...
|
by: Steven T. Hatton |
last post by:
The reason Stroustrup warns against using set and get functions is that an
object of class type should be designed in such a way as to maintain some
invariant. All operations on the class should be such that they maintain
the invariant. An example is a std::vector<>. The invariant can be state
as: a std::vector<T> hold a number of elements given by the return value of
the member function std::vector<T>::size(). This means that adding or...
|
by: Zap |
last post by:
Widespread opinion is that public data members are evil, because if you
have to change the way the data is stored in your class you have to
break the code accessing it, etc.
After reading this (also copied below for easier reference):
http://groups.google.it/groups?hl=en&lr=&safe=off&selm=6beiuk%24cje%40netlab.cs.rpi.edu&rnum=95
I don't agree anymore.
|
by: Joe Van Dyk |
last post by:
Say I have the following class:
using std::string;
class Player
{
public:
Player() : name(""), age(""), other_stuff("") {}
private:
string name;
string age;
| |
by: mystilleef |
last post by:
Hello,
What is the Pythonic way of implementing getters and setters. I've
heard
people say the use of accessors is not Pythonic. But why? And what is
the alternative? I refrain from using them because they smell
"Javaish."
But now my code base is expanding and I'm beginning to appreciate the
wisdom behind them. I welcome example code and illustrations.
|
by: bearophileHUGS |
last post by:
I have started doing practice creating C extensions for CPython, so
here are two ideas I have had, possibly useless.
If you keep adding elements to a CPython dict/set, it periodically
rebuilds itself. So maybe dict.reserve(n) and a set.reserve(n) methods
may help, reserving enough (empty) memory for about n *distinct* keys
the programmer wants to add to the dict/set in a short future. I have
seen that the the C API of the dicts doesn't...
|
by: andrewfelch |
last post by:
Hello all,
I'm using the metaclass trick for automatic reloading of class member
functions, found at: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/160164
My problem is that if I
1) pickle an object that inherits from "AutoReloader"
2) unpickle the object
3) modify one of the pickled' object's derived class methods
4) reload the module holding the class
|
by: |
last post by:
Hello all,
I have a question which might be simple or need some work around.
I want to do something like this. My class/instance has a dict as a
property. I want the instance to catch the change in the dict (change
in some values, addition/deletion of key/value etc) to be recognized by
the class instance.
How can I do this? Any suggestions are very well appreciated.
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |