I first hit Python and am stuck here:
class A:
def __init__(self):
a = foo("baa")
class B(A):
b = foo("boo")
def foo(string):
return string
At this moment I upload the above file (with a name classes
), and this happens:
$ python
Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from classes import *
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "classes.py", line 5, in <module>
class B(A):
File "classes.py", line 6, in B
b = foo("boo")
NameError: name 'foo' is not defined
Notice how the error is in class B, where it foo
is called directly, not from __init__
. Note also that I have not created an instance of the class yet B
.
First question:
- Why is he returning an error? I do not create a class.
Moving. The "problem" is solved by moving the definition of a foo()
few lines above:
def foo(string):
return string
class A:
def __init__(self):
a = foo("baa")
class B(A):
b = foo("boo")
Now i can do
>>> x = B()
>>> x.b
'boo'
but i can't do
>>> y = A()
>>> y.a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: A instance has no attribute 'a'
Additional questions:
- What didn’t I understand about
__init__
?
I do not think this is the same as the declaration , so I hope this question is not a duplicate.
, DSL, , python.