問題描述
我有以下代碼:
import numpy as np
class ClassProperty(property):
def __get__(self, cls, owner):
return self.fget.__get__(None, owner)()
def coord(cls, c):
if cls.dimension <= 2:
return c
else:
return c + [0]*(cls.dimension-2)
class Basis_NonI(object):
@ClassProperty
@classmethod
def zerocoord(cls):
return coord(cls, [0,0])
def __init__(self, dimension):
pass
class Basis_D(Basis_NonI):
dimension = 2
proj_matrix = np.array([Basis_D.zerocoord, Basis_D.zerocoord])
def __init__(self, dimension):
super(Basis_D, self).__init__(Basis_D.dimension)
基本上我希望 dimension
和 proj_matrix
成為 Basis_D
的類屬性.
where basically I want dimension
and proj_matrix
to be class attributes of Basis_D
.
當我運行它時,出現以下錯誤:
When I run it, the following error is given:
proj_matrix = np.array([Basis_D.zerocoord, Basis_D.zerocoord])
proj_matrix = np.array([Basis_D.zerocoord, Basis_D.zerocoord])
NameError:名稱Basis_D"未定義
NameError: name 'Basis_D' is not defined
--
我不明白的是,我可以在init
中使用Basis_D.dimension,那么為什么在我使用它來定義時它不能識別名稱Basis_D
proj_matrix
?
What I don't understand is that I can use Basis_D.dimension in the init
, so why does it not recongise the name Basis_D
when I use it to define proj_matrix
?
推薦答案
class
是一個可執行語句.首次導入模塊時(對于給定進程),執行 class
語句頂層的所有代碼,以這種方式定義的所有名稱都收集到一個字典中,然后 >class
對象是用這個dict創建的,最后綁定到類名上.IOW,此時:
class
is an executable statement. When the module is first imported (for a given process), all the code at the top-level of the class
statement is executed, all names defined that way are collected into a dict, then the class
object is created with this dict, and finally bound to the class name. IOW, at this point:
class Basis_D(Basis_NonI):
dimension = 2
# HERE
proj_matrix = np.array([Basis_D.zerocoord, Basis_D.zerocoord])
該類尚未創建,也未綁定到名稱Basis_D
.
the class has not yet been created nor bound to the name Basis_D
.
現在調用 __init__
時,該類已經創建并綁定到模塊級名稱 Basis_D
,因此可以解析名稱.
Now by the time __init__
is called, the class has already been created and bound to the module-level name Basis_D
, so the name can be resolved.
FWIW,你不應該在你的方法中直接引用 Basis_D
,而是 type(self)
(甚至是 self
- 如果一個名字沒有解析為實例屬性,而是在類中查找).
FWIW, you shouldn't directly reference Basis_D
in your methods, but type(self)
(or even self
- if a name is not resolved as an instance attribute, it's looked up on the class).
另外,你為什么堅持使用類屬性?您是否了解您的 project_matrix
數組將在 Basis_D
的所有實例之間共享?
Also, why do you insist on using class attributes ? Do you understand that your project_matrix
array will be shared amongst all instances of Basis_D
?
這篇關于NameError:未在類本身內部定義的類的名稱 - python的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!