我让我的头周围的Python是第一次,我被困在这里: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'
而且问题:
- 什么是我h大约不知道
__init__
?
我不认为这是一样的forward declaration,因此我希望这个问题不是重复的。
另一方面,我的目标是实现一个DSL,但这主要是让我自己学习python的借口。
什么是麻烦? :) – senderle
这是一个字符串输入非常快。 – Dimitry
确实:) - +1的方式。 – senderle