newb __init__ inheritance
Chris Rebert
clp2 at rebertia.com
Sun Mar 11 07:37:55 EDT 2012
On Sun, Mar 11, 2012 at 3:56 AM, hyperboogie <hyperboogie at gmail.com> wrote:
> On Sunday, March 11, 2012 12:38:27 PM UTC+2, Chris Rebert wrote:
>> On Sun, Mar 11, 2012 at 3:18 AM, hyperboogie wrote:
>> <snip>
>> > thank you everyone...
>> > Still things are not working as expected... what am I doing wrong?
>> <snip>
>> > # cat test.py
>> > #!/usr/bin/python
>> >
>> > class A():
>>
>> You should be subclassing `object`, but that's a minor point which
>> isn't the cause of your problem.
>>
>> > def __init__(self):
>> > z=1
>>
>> This creates a *local variable* named "z". You want an *attribute*
>> named "z", so you should be doing:
>> self.z = 1
>> instead. Same problem elsewhere; you must *always* explicitly use
>> `self` when referencing an attribute of the current object. Python !=
>> Java or C++.
>>
>> Cheers,
>> Chris
>
> Thanks ... works great now.
> Two last questions:
>
> 1. What do you mean by "subclassing `object`"?
Your classes should (ultimately) subclass the built-in class named
"object". In your case:
class A(object):
# …rest same as before…
This ensures that your classes are new-style rather than old-style
(the latter is deprecated); see:
http://docs.python.org/glossary.html#term-new-style-class
> 2. Is the mro function available only on python3?
There's never been an mro function. Perhaps you mean the __mro__
attribute of classes (e.g. `B.__mro__`), which is available in Python
2.2+ and Python 3?
Cheers,
Chris
More information about the Python-list
mailing list