473,804 Members | 2,758 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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__.h as_key( item ):
self.__dict__[item] = kwargs[item]
else:
pass
## init all parents...
parents = self.__class__. __bases__
if parents:
for i in range(len(paren ts)):
apply(parents[i].__name__.__ini t__,\ (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(paren ts)):
apply(parents[i].__name__.__ini t__,\ (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 1603
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.Obj ectClass, 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.Obj ectClass, 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
2404
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 relevant announcements. If you're interested, drop me a note. But if for some reason you think that this discussion is fine here at the c.l.py, please let me know. ** LONG POST AHEAD **
6
1450
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 eventually replace generic objects with concrete classes, but I'm certainly willing to do some of the work writing it up, etc. If you're interested in helping me, let me know (off-list). Some quotes from this thread: Hung Jung Lu wrote:
2
1496
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, the constructor call will still > | call its __init__ method. If you return an object of a different
2
3005
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 ################################## class test: def __init__(self): exec("def dfunc(msg):\n\tprint msg\nprint 'exec def function'") dfunc('Msg in init ...') # it work
3
5151
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__(..)' . However, trying to do so results in a 'TypeError: super() argument 1 must be type, not classobj'. Now, if I use 'Exception.__init__(..)' instad of super(..)... ,everything
10
2321
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 call to work? Exists is a method within the Swatch class NOT the SwatchPanel class. Is this possible? Suggestions would be very welcome.
3
1650
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
2679
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 "Parent1 init called." self.x = 10 class Parent2(object):
4
1155
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 itertools.count.__init__.__doc__, while itertools.count.__doc__ is the informative doc-string ("DS" henceforth): """count() --count object
0
9705
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, 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...
0
9576
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,...
0
10323
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 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...
0
10074
tracyyun
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...
1
7613
isladogs
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...
0
6847
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();...
0
5516
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...
1
4292
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2988
bsmnconsultancy
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...

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.