Beginner's Question (or bug in python?)

Dennis Baker drbaker at softhome.net
Fri Apr 20 13:01:57 EDT 2001


On Fri, 20 Apr 2001 16:47:52 +0200 Rolf Magnus <ramagnus at zvw.de> wrote:

I Think what you want to do is below... Your problem with the naming (Fred vs
Hans) is probably due to running the application in the IDE, most of the Python
IDEs do not clear out the namespace when you rerun a script so it was probably 
just due to a poluted namespace... 

Incidentally, I'm pretty green so you might want to review the Tutorial:
http://python.org/doc/current/tut/node11.html#SECTION0011310000000000000000

) class Fred:
) 
)         def __init__(self):
)                 print('initializing fred')
) 
)         def __del__(self):
)                 print('deleting fred')
) 
)         def test(self):
)                 print('Hello world')
) 
) 
) class Foo(Fred):
I think you just wanted to create a new class (No inheritance from Fred) 
so it would be thus:
  class Foo:
) 
)         def __init__(self):
)                 Fred.__init__(self)

To create a new instance of Fred you would do this:
		  self.f = Fred()
The __init__ and __del__ methods are called implicitly in the declaration of
the class you don't need to call them.  Also,  you would never pass self to
a class (Unless you wanted to pass the current instance of the current class)

)                 print ('initializing foo')
) 
)         def __del__(self):
)                 print('deleting foo');
)                 Fred.__del__(self)

The self.f instance of Fred will be deleted implicitly when you delete this 
instance of Foo.  However if you wanted to explicitly delete it you would do
it like this :
		  del self.f

) 

This line will now create a new instance x of the class Foo.
) x = Foo()
The __init__ function will implicitly create an instance (self.f) of class 
Fred which can be referenced so:
  x.f.test()
and deleted so:
  del x

When you execute this it will always output :
initializing fred
initializing foo
Hello world
deleting foo
deleting fred

A completely rewritten version would look like this:

class Fred:

        def __init__(self):
                print('initializing fred')

        def __del__(self):
                print('deleting fred')

        def test(self):
                print('Hello world')

class Foo:

        def __init__(self):
                self.f = Fred()
                print ('initializing foo')

        def __del__(self):
                print('deleting foo');
                # instance of Fred will be deleted inherantly

x = Foo()
x.f.test()

del x

-- Dennis 




More information about the Python-list mailing list