问题描述
在python 3中,我发现class属性可用作__init__()
函数中的参数,如下所示:
In python 3 I found that class attribute can be used as a argument in __init__()
function, like below:
文件test.py:
class Foo:
var1 = 23333
def __init__(self, var=var1):
self.var = var
以cmd运行:
C:\Users\rikka\Desktop>py -3 -i test.py
>>> f1=Foo()
>>> f1.var
23333
但是通过使用dot.expression,在初始化此类时,解释器将报告错误:
but by using a dot.expression, when init this class, interpreter will report an error:
文件test2.py:
file test2.py:
class Foo:
var1 = 23333
def __init__(self, var=Foo.var1):
self.var = var
以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
我只是不知道为什么解释器找不到名称"Foo",因为Foo是环境中全局框架中的名称.关于Python类,我是否有不完全了解的范围相关概念?
I just don't know why interpreter cannot find name 'Foo' since Foo is a name in the global frame in the environment. is there something scope related concept about python class that I don't fully understand?
推荐答案
函数默认设置是在函数定义时间设置的,而不是在调用时设置的.这样,存储的不是表达式var1
,而是变量表示的 value .定义函数时,var1
恰好是局部变量,因为在构建类时,将类主体中的 all 名称视为函数中的局部变量,但名称Foo
却没有之所以存在,是因为该课程尚未完成构建.
Function defaults are set at function definition time, not when being called. As such, it is not the expression var1
that is stored but the value that variable represents, 23333
. var1
happens to be a local variable when the function is defined, because all names in a class body are treated as locals in a function when the class is built, but the name Foo
does not yet exist because the class hasn't finished building yet.
改为使用前哨,并在函数正文中使用 ,然后确定Foo.var1
的当前值:
Use a sentinel instead, and in the body of the function then determine the current value of Foo.var1
:
def __init__(self, var=None):
if var is None:
var = Foo.var1
self.var = var
在这里,我将None
用作哨兵,因为它很容易获得,不需要经常作为实际值.如果确实需要将var
设置为不同的值(即非默认值),请使用其他单例哨兵:
I used None
as the sentinel here because it is readily available and not often needed as an actual value. If you do need to be able to set var
as a distinct (i.e. non-default) value, use a different singleton sentinel:
_sentinel = object()
class Foo:
var = 23333
def __init__(self, var=_sentinel):
if var is _sentinel:
var = Foo.var1
self.var = var
这篇关于python class属性不能用作构造函数的参数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!