Python 类内函数的前向声明

发布于 2024-10-20 11:13:38 字数 1587 浏览 2 评论 0原文

我第一次了解 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__?

我认为这与前向声明不同,因此我希望这个问题不是重复的。

顺便说一句,我的目标是实现 DSL,但这主要是让自己学习 python 的借口。

I am getting my head around Python for the first time and I am stuck here:

class A:
    def __init__(self):
        a = foo("baa")

class B(A):
    b = foo("boo")

def foo(string):
    return string

At this point I load the above file (named 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 foo is called directly and not from __init__. Notice also how I have not yet instantiated the class B.

First question:

  • Why is it returning an error? I am not instantiating a class.

Moving on. The 'problem' is solved by moving the definition of foo() a 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'

Further questions:

  • What is that I have not understood about __init__?

I don't think this is the same as a forward declaration, hence I hope this question is not a duplicate.

On a side note, I am aiming towards implementing a DSL, but that's mostly an excuse to get myself to learn python.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

浅笑依然 2024-10-27 11:13:38

首先,在类 B 中,函数 foo() 在声明之前被调用。 A 不存在此问题,因为 foo() 仅在实例化类时(定义函数 foo 之后)才会调用。

对于你的第二个问题, ya 不会工作,因为你没有说 self.a = foo('stirng') 。 a = foo('stirng') 仅在 __ init __ 范围内创建变量 a。

理想的 __ init __ 函数将变量分配给实例 self

First, in class B, the function foo() is called before being declared. A does not have this problem because foo() is only called when the class is instantiated--after the function foo is defined.

For your second question, y.a will not work because you did not say self.a = foo('stirng'). a = foo('stirng') only creates the variable a in the scope of __ init __.

An ideal __ init __ function assigns variables to the instance self.

冷情妓 2024-10-27 11:13:38

您不了解 __init__ 的事情是,它仅在您实例化(即创建类 A)时才会被调用。由于代码中没有任何地方实际创建了此类的实例,因此您永远不会调用它的初始化程序,因此永远不会遇到前向声明。

一般来说,前向声明在 Python 中不是问题,因为只有在调用必要的函数时才会评估引用。这里的问题是类定义在定义时执行。更具体地说,当 Python 解释器遇到 class 语句时会发生以下情况:

  • 它定义一个新的命名空间(局部变量的字典)来保存所有代码。
  • 它执行类定义中的代码。
  • 它将存储在本地命名空间中的任何内容放入类 __dict__ 中。
  • 它关闭新的命名空间并将新类添加到模块命名空间。

当然,您不需要知道这一点来定义类;只需知道这一点即可。您只需要记住,类定义中的任何内容都将在类首次定义时执行! (这很少是一个问题,因为类级变量一开始就不那么常见,并且通常不需要在定义时动态设置。)

这个问题也会在函数定义中出现:当你这样做时

def foo(x=bar()): pass

那么 bar 将在定义 foo 时被调用一次,并且不再调用。


尝试运行以下代码,看看它是否能澄清问题:

class A():
    def __init__(self):
        self.a = foo()

a = A()

def foo():
    pass

The thing you haven't understood about __init__ is that it is only called when you instantiate (i.e. make an instance of) class A. Since nowhere in your code have you actually made an instance of this class, you never call its initialiser and hence never run into the forward declaration.

In general forward declarations aren't a problem in Python, because the reference is only evaluated when you call the necessary function. The problem here is that class definitions are executed at define-time. More, specifically, here's what happens when the Python interpreter meets a class statement:

  • It defines a new namespace (dictionary of local variables) to hold all the code.
  • It executes the code inside the class definition.
  • It puts anything stored into the local namespace into the class __dict__.
  • It closes the new namespace and adds the new class to the module namespace.

Of course, you don't need to know that to define a class; you just need to remember that anything inside a class definition will be executed when the class is first defined! (This is rarely a problem, because class-level variables aren't that common in the first place, and don't usually need to be set dynamically at define-time.)

This issue also pops up in function definitions: when you do

def foo(x=bar()): pass

then bar will be called once, at the time foo is defined, and never again.


Try running the following code and see if it clarifies things:

class A():
    def __init__(self):
        self.a = foo()

a = A()

def foo():
    pass
执笔绘流年 2024-10-27 11:13:38
class A:
    def __init__(self):
        a = foo("baa")

class B(A):
    b = foo("boo")

a 是一个实例属性 - 每个 A 都有自己的变量,并且 foo("baa") 仅在创建 A 对象时才会计算。

b 是一个类属性 - 每个 B 对象共享 b 的相同副本,并且 foo("boo") 在定义类时进行评估。

一般来说,您可以引用尚不存在的函数和类,只要它们在您评估引用之前(即在您实际尝试调用函数之前)定义即可。 )。

class A:
    def __init__(self):
        a = foo("baa")

class B(A):
    b = foo("boo")

a is an instance attribute - each A has its own a variable, and foo("baa") is only evaluated when you create an A object.

b is a class attribute - every B object shares the same copy of b, and foo("boo") is evaluated when the class is defined.

In general, you can make references to functions and classes which do not yet exist so long as they get defined before you evaluate the reference (ie before you actually try calling the function).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文