我正在嘗試創建一個具有從多個文件中讀入的各種數據的類。通常的方法可能是定義構造函數(__init__
),本程序讀取裏面的數據,例如,Python類的頭部分中的可執行語句
from SomeOtherMod import reader # some data reader
class Myclass:
def __init__(self):
self.N = reader.readN()
self.data = reader.readdata()
self.foo = self.data.foo()
self.bar = self.data.bar()
... # more data to read and associated properties follow
def othefunc(self):
... # use self.N, self.data, ...
但它也似乎我可以寫在類的頭部分同樣的事情,而無需使用__init__
,例如,
class Myclass:
N = reader.readN()
data = reader.readdata()
foo = data.foo()
bar = data.bar()
...
def otherfunc(self):
...
看起來比第一個代碼更簡潔。所以我想知道這個第二個代碼是否是定義Python類的各個領域的有效方法?這是否被認爲是不好的做法,或者第一種方法和第二種方法有什麼區別?我將不勝感激任何建議,因爲我仍然是Python的新手。非常感謝!
第一種方法定義實例屬性,它可以在類的實例之間變化。第二種方法定義了類將被該類的所有實例共享的類屬性。 [9。類(https://docs.python.org/3/tutorial/classes.html)。 ... https://docs.python.org/3/reference/datamodel.html – wwii
你可以考慮像Java或C++語言中的「靜態屬性」類的屬性 –
嗯,真的...... Acutually,當我讀關於Python的一些入門書籍,我仍然無法理解Python中的實例和類字段如何區分(語法),除了用法{Classname}。{fieldname}。我將檢查更多... – septc