Question about instance creation

Gordon McMillan gmcm at hypernet.com
Mon Mar 20 16:53:01 EST 2000


Robin Barendregt writes:

> I hope that I'm not totally non-sensical here.

Well I'm not making any sense of it.

First you asked:

> class Class3(Class1, Class2):
>     def __init__(self):
>         Class1.__init__(self)
>         Class2.__init__(self)
>         print 'Class3 init'
>         c = DynamicClass(Class1, "arg given")
>         print c
>         self.var3 = 'this is var3'
...
> I want the var c in Class3.__init__ to contain and instance of 
the
> class given as 1st argument to DynamicClass. I tried using 
return in
> the DerivedClass.__init__ but I get an exception saying I 
should
> return None in an __init__. How can I accomplish this?

And the answer is obvious - forget DynamicClass and just
  c = Class1("arg given")
(though I can't see any sense to this, especially since you're 
not saving a reference).

But then you said

> I'm sorry. What I meant was that I want c to contain an 
instance of
> DerivedClass, of course.

which means ignore the above advice, because it already does.

and finally you say:

> ...In class2.py, the definition for DynamicClass should
> be:
> 
> class DynamicClass:
>     def __init__(self, newAlias, *args):
>         global BaseAlias
>         BaseAlias = newAlias
>         apply(DerivedClass, args)
> 

which is legal, but makes no sense.

So, I haven't the foggiest idea *what* you're trying to do. 
However, this might help clarify things.

Once Python hits a class statement:
class Spam:
  ...
it creates a class object (named "Spam"). When you create 
an instance of Spam by using "Spam(...)", Python creates an 
instance object whose attribute "__class__" points to the 
Spam class object. As the final step, Python invokes Spam's 
"__init__" method on the instance. At this point "self" already 
exists and is complete, just uninitialized. You can't mess with 
the value of "self" at all.

If you're brave, you can mess with what the "__class__" 
attribute contains, and what "__class__.__bases__" contains. 
It's kind of fun once in awhile, but it introduces enough 
surprises that sane people stay away from it.

As far as aliases go:

class Spam:
  pass

Eggs = Spam

You can now create instances of "Eggs" and they will be 
identical to similarly created instances of "Spam", because 
"Eggs" is just another label for "Spam".

>>> class Spam:
...  pass
...
>>> Eggs = Spam
>>> e = Eggs()
>>> e
<__main__.Spam instance at 7fa4d0>
>>>

Does this help?

- Gordon




More information about the Python-list mailing list