【发布时间】:2011-03-06 20:27:39
【问题描述】:
我第一次接触 Python,却被困在这里:
class A:
def __init__(self):
a = foo("baa")
class B(A):
b = foo("boo")
def foo(string):
return string
此时我加载了上面的文件(名为classes)并且发生了这种情况:
$ 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
注意 B 类中的错误,其中 foo 是直接调用的,而不是从 __init__ 调用的。还要注意我还没有实例化类B。
第一个问题:
- 为什么返回错误?我没有实例化一个类。
继续前进。通过将foo() 的定义移到上面几行来解决“问题”:
def foo(string):
return string
class A:
def __init__(self):
a = foo("baa")
class B(A):
b = foo("boo")
现在可以了
>>> x = B()
>>> x.b
'boo'
但我做不到
>>> y = A()
>>> y.a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: A instance has no attribute 'a'
其他问题:
-
__init__有什么我不明白的地方?
我不认为这与forward declaration 相同,因此我希望这个问题不是重复的。
顺便说一句,我的目标是实现 DSL,但这主要是让自己学习 Python 的借口。
【问题讨论】:
标签: python class-design forward-declaration