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.
Jul 18 '05
12 2018
Nick Craig-Wood <ni**@craig-wood.com> wrote in message news:<sl******* **********@iris hsea.home.craig-wood.com>... 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
To me, it appears the Christopher is simply looking for a way to
get/set members of a dictionary using a different syntax.
That being the case, why not create a pythonic solution like the one
above using new style classes, as we can derive directly from the dict
type?
In this case, we will just forward the __getattr__ and __setattr__
calls to __getitem__ and __setitem__, respectively.
Here is the equivalent solution:
class MyClass (dict): #New style class derived from dict
type
#Use same get/set syntax desired during construction
def __init__(self):
self.one = 1
self.two = 2
self.three = 3
#Get/set syntax changed with simple forwarding functions
def __getattr__(sel f, key):
return self.__getitem_ _(key)
def __setattr__(sel f, key, value):
self.__setitem_ _(key, value)
Isn't this the type of thing that Guido van Rossum envisioned in
trying to unify types and classes?
Michael Loritsch
Jeff Shannon <je**@ccvcorp.c om> wrote:
... >>> class MyClass(object) :
... def __init__(self): ... self.__dict__['m_dict'] = {'one':1, 'two':2, 'three':3}
Incidentally, I suspect
object.__setatt r__(self, 'm_dict', dict(one=1, two=2, three=3))
is preferable to working on self.__dict__ overtly, when self's class is
newstyle, at least (though I think it might work with classic classes
too). It should come down to the same effect in normal cases, but might
work better if (e.g.) there's a __slots__ = ['m_dict_'] somewhere;-).
Alex
Michael Loritsch <lo******@gmail .com> wrote:
... class MyClass (dict): #New style class derived from dict type
#Use same get/set syntax desired during construction def __init__(self): self.one = 1 self.two = 2 self.three = 3
#Get/set syntax changed with simple forwarding functions def __getattr__(sel f, key): return self.__getitem_ _(key) def __setattr__(sel f, key, value): self.__setitem_ _(key, value)
Isn't this the type of thing that Guido van Rossum envisioned in trying to unify types and classes?
Any deliberate seeding of confusion between items and attributes will
eventually cause grief, IMHO. Specifically, I'd find it unnerving that
after foo=MyClass(), some foo[x]=y for runtime read/computed values of x
and y may make all kinds of methods unaccessible on foo -- say
foo.keys(), foo.pop(), and so on. Basically, any such foo would need to
be only ever accessed by implied lookup of special methods (working on
the class, and not the instance, fortunately), and never by any name
lookup of a method on the instance itself. Looks like a deliberate
attempt to put oneself in a fragile, error-prone situation. Maybe I'm
just a pessimist!
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: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
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: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
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: 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...
| |