Movatterモバイル変換


[0]ホーム

URL:


Beginner's Question (or bug in python?)

Dennis Bakerdrbaker 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 vsHans) is probably due to running the application in the IDE, most of the PythonIDEs 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 ofthe class you don't need to call them.  Also,  you would never pass self toa 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 doit 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 xWhen you execute this it will always output :initializing fredinitializing fooHello worlddeleting foodeleting fredA 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 inherantlyx = Foo()x.f.test()del x-- Dennis


More information about the Python-listmailing list

[8]ページ先頭

©2009-2025 Movatter.jp