473,386 Members | 1,817 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

hmm, lets call it: generic __init__ problem

Hi list,

in the course of writing a small app, I tried to design a class, which
would allow to derive its behaviour solely from its name, so that I
would be able to write one abstract class with the logic and get
different objects/instances by subclassing with appropriate names.
Consider the following:

ATTRS = {'one':['attr1', 'attr2'],
'two':['attr3','attr4'],
'three':['attr5','attr6'],
'four':['attr7','attr8']}
class one:
def __init__(self, *args, **kwargs):
## get allowed attributes...
for attr in ATTRS[self.__class__.__name__]:
self.__dict__[attr] = ''

## unknown attributes are silently ignored...
for item in kwargs.keys():
if self.__dict__.has_key( item ):
self.__dict__[item] = kwargs[item]
else:
pass
## init all parents...
parents = self.__class__.__bases__
if parents:
for i in range(len(parents)):
apply(parents[i].__name__.__init__,\ (self,)+args, kwargs)

class two(one):
def foo(self):
pass

class three(one):
def bar(self):
pass

class four(two, three):
def wiskey_bar(self):
pass

So running:
o = funClass.one()
dir(o) ['__doc__', '__init__', '__module__', '__str__', 'attr1', 'attr2'] o.attr1 ''

and: o = funClass.one( attr1='spam', attr2='chicks')
o.attr2 'chicks'

but: dir(o)

['__doc__', '__init__', '__module__', '__str__', 'attr7', 'attr8',
'bar', 'foo', 'wiskey_bar']

I expected to have all attrs from all parents initialized from:
parents = self.__class__.__bases__
if parents:
for i in range(len(parents)):
apply(parents[i].__name__.__init__,\ (self,)+args, kwargs)

in the __init__ method. But apparently I have misunderstood the
self.__class__.__bases__ thingy as it does not do what I want ;(

Apart from the obvious mistake I can't figure out:
1) Is this intelligent at all?
2) Is there a better way to do it?
3) How do you change tabwidth in mozilla mail?

thanks
Paul
Jul 18 '05 #1
3 1577
Michele Simionato wrote:
This is probably not what you want:

It's not about importing attributes rather than having only one
definition of __init__ in one "metaclass" wich should behave differently
dependent on the name of the subclass (see my answer to Peter). I
found out I have to read lots of stuff to catch up with concepts of
new-style classes and metaclass design.

The solution using super() like Peter suggested is almost perfect
except the name of the class is still hardcoded inside of __init__.

one(object):
def __init__(self, *args, **kwargs):
super(one, self).__init__()
^^^^
r = self.s.get_obj(ldap.schema.ObjectClass, self.__class__.__name__)
...process r...

implies to write another __init__ for every subclass, since "one" wouldn
't match the subclass's name right? Instead of "one" I'd like to have
something that get's the current class at instantiation time. Is that
possible ?

thanks a lot for all your time and help.
Paul
Jul 18 '05 #2
paul kölle <ko*****@uni-weimar.de> wrote in message news:<c1*************@ID-131134.news.uni-berlin.de>...
The solution using super() like Peter suggested is almost perfect
except the name of the class is still hardcoded inside of __init__.

one(object):
def __init__(self, *args, **kwargs):
super(one, self).__init__()
^^^^
r = self.s.get_obj(ldap.schema.ObjectClass, self.__class__.__name__)
...process r...

implies to write another __init__ for every subclass, since "one" wouldn
't match the subclass's name right? Instead of "one" I'd like to have
something that get's the current class at instantiation time. Is that
possible ?


Yes, but it is quite non-trivial to get it right with the current
language.
I consider it to be a wart of super. See Guido's "autosuper" metaclass
and this post of mine for a solution:

http://groups.google.it/groups?hl=it....lang.python.*

Warning: it is not for the faint of heart ;)

Michele Simionato
Jul 18 '05 #3
paul kölle <ko*****@uni-weimar.de> wrote in message news:<c1*************@ID-131134.news.uni-berlin.de>...
<snip considerations about super>

It came to my mind that you may want to read this post of mine (how
to make __init__ calling super automagically):

http://groups.google.it/groups?hl=it....lang.python.*

It does not solve your problem but it can give you some idea.
HTH,

Michele
Jul 18 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: Carlos Ribeiro | last post by:
Hello all, I'm posting this to the list with the intention to form a group of people interested in this type of solution. I'm not going to spam the list with it, unless for occasional and...
6
by: Steven Bethard | last post by:
So I thought I'd try to summarize a few things here and maybe we can move toward filing a PEP. I'm not really sure I'm the right person to champion it because, as I've mentioned, I usually...
2
by: Steven Bethard | last post by:
Felix Wiemann wrote: > Steven Bethard wrote: >> http://www.python.org/2.2.3/descrintro.html#__new__ > > > I'm just seeing that the web page says: > > | If you return an existing object,...
2
by: FAN | last post by:
I want to define some function in python script dynamicly and call them later, but I get some problem. I have tried the following: ################################## # code...
3
by: chriss | last post by:
Hi, environment: Python 2.4, GNU/Linux, kernel 2.6.12.2 having subclassed 'Exception' I'm trying to call the initialiser __init__(...) of the superclass Exception with 'super(..).__init__(..)'...
10
by: steve bull | last post by:
I have a class SwatchPanel which takes Swatch as a parameter type. How can I call a static function within the Swatch class? For example the code below fails on TSwatch.Exists. How can I get the...
3
by: Luis P. Mendes | last post by:
Hi, I have the following problem: I instantiate class Sistema from another class. The result is the same if I import it to interactive shell. s = Sistema("par") class Sistema:
3
by: 7stud | last post by:
When I run the following code and call super() in the Base class's __init__ () method, only one Parent's __init__() method is called. class Parent1(object): def __init__(self): print...
4
by: Tal Einat | last post by:
Hi all, I just ran into this. In IDLE (Python 2.5), the call-tip for itertools.count is: "x.__init__(...) initializes x; see x.__class__.__doc__ for signature" That's...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
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,...
0
Oralloy
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,...
0
jinu1996
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...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.