![](/img/trans.png)
[英]Python 2.7, defining a base class with attributes, id with init constructor
[英]python 2.7 defining a class that will show their attributes if called with no arguments
我有這樣的課:
class DATA:
# class for the data
def __init__(self, filename):
f_in = open(input_file, 'r')
data = json.load(f_in)
f_in.close()
# organizational data
self.T = data['temperature']
self.appVersion = data['appVersion']
我可以使用以下方法創建該類的對象:
D = DATA(filename)
我可以使用
D.T
該類將具有很多屬性,而我很快就會忘記它們的名稱...如果我一個人叫D
,我需要的是提示一些有用的信息。
例如:
>>>D
The attributes of D are:
- T (X)
- appVersion (Y)
其中X
和Y
是對應的值。
是否有實現此目標的方法? 還是其他(更好)的方法?
謝謝。
您可以在文檔字符串中記錄屬性:
class DATA(object):
"""this says something about the object.
Attributes:
T: ...
"""
...
現在,您可以訪問您編寫的文檔:
help(DATA)
要么:
print(DATA.__doc__)
如果您想要精確的功能,鍵入時會得到什么
>>> D
是DATA.__repr__(D)
的return
值:
class D(object):
def __init__(self, ...):
...
def __repr__(self):
s = "The attributes of D are:\n- T ({0.T})\n- appVersion ('{0.appVersion}')"
return s.format(self)
用法示例(使用覆蓋的__init__
直接獲取data
):
>>> D = DATA({'temperature': 102, 'appVersion': '1.0.4'})
>>> D
The attributes of D are:
- T (102)
- appVersion ('1.0.4')
但是,您應該注意,這是對__repr__
的濫用。 從文檔中 :
如果可能的話,[
__repr__
]應該看起來像一個有效的Python表達式,可以用來重新創建具有相同值的對象(在適當的環境下)。 如果這不可能,則應返回格式為<...some useful description...>
的字符串。
因此,其他答案更像Pythonic。
您可以使用__dict__
屬性:
class Data:
def __init__(self):
self.foo = 'value 1'
self.bar = 'value 2'
d = Data()
print(d.__dict__)
打印:
{'bar': 'value 2', 'foo': 'value 1'}
要在提示符下輕松訪問它,請嘗試以下操作:
def info(obj):
print(obj.__dict__)
然后在提示符下,鍵入:
info(d)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.