2017-06-30 2 views
0

Python3.5でクラス変数を宣言するときに、他のクラス変数を参照することに興味深いものが見つかりました。 Python2.7で発生するようには見えず、Python3.5でも、コードにエラーがないと解釈されることがありました。誰もが問題を知っていますか?Pythonクラス変数が見つかりません

macOS:~ $ python3.5 
Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 26 2016, 10:47:25) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin 
Type "help", "copyright", "credits" or "license" for more 
information. 
>>> class A: 
...  x = 1 
...  y = x+1 
... 
>>> class B: 
...  x = 1 
...  y = [i+x for i in range(0,3)] 
... 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "<stdin>", line 3, in B 
    File "<stdin>", line 3, in <listcomp> 
NameError: name 'x' is not defined 
>>> 
+0

dupe of https://stackoverflow.com/questions/22797782/scope-of-class-variable-with-list-comprehension – pvg

+0

ああ、私の悪いです。リンクありがとう。 – wjgan

答えて

-1

変数に正しい方法で対処しましたか?

print(A.x) 

たとえば、var xのコードに適切な出力が表示されます。

関連する問題