小编mic*_*ang的帖子

python类属性不能用作构造函数的参数?

在python 3中,我发现class属性可以在__init__()函数中用作参数,如下所示:

file test.py:

class Foo:
    var1 = 23333
    def __init__(self, var=var1):
        self.var = var
Run Code Online (Sandbox Code Playgroud)

在cmd中运行:

C:\Users\rikka\Desktop>py -3 -i test.py
>>> f1=Foo()
>>> f1.var
23333
Run Code Online (Sandbox Code Playgroud)

但是通过使用dot.expression,当init这个类时,解释器将报告错误:

文件test2.py:

class Foo:
    var1 = 23333
    def __init__(self, var=Foo.var1):
       self.var = var
Run Code Online (Sandbox Code Playgroud)

在cmd中运行:

C:\Users\rikka\Desktop>py -3 -i test2.py
Traceback (most recent call last):
  File "test2.py", line 1, in <module>
    class Foo:
  File "test2.py", line 3, in Foo
    def __init__(self, var=Foo.var1):
NameError: name 'Foo' is not defined
Run Code Online (Sandbox Code Playgroud)

我只是不知道为什么解释器找不到名字'Foo',因为Foo是环境中全局框架中的名字.有什么关于python类的范围相关的概念,我不完全理解?

python constructor arguments class class-attributes

0
推荐指数
1
解决办法
86
查看次数

标签 统计

arguments ×1

class ×1

class-attributes ×1

constructor ×1

python ×1