0
我有一個Python類,其屬性爲_mylist
。當我通過名稱呼叫MyClass
時,我想要返回_mylist
的實例。以下是我想要定義的基本概念,後面跟着示例輸入和輸出。當按名稱調用Python類實例時設置返回值
class MyClass:
def __init__(self, a, b):
self._mylist = [a, b]
def _returnlist(self):
# method conferring MyClass with the property that calls to class
# instances returns self._mylist
pass
>>> mc = MyClass(a, b)
>>> mc # the desired property: call to mc returns mc._mylist
[a, b]
>>> k = mc # assignment from mc instance only assigns mc._mylist
>>> k
[a, b]
是否有標準的方法來給這個類的這個屬性?
不,你不能那樣做。這樣做也沒有意義;它如何知道你何時想訪問該列表以及實際實例? – jonrsharpe
號爲什麼要這樣做?只需*使用列表* –
覆蓋'__str__'方法可能是一種方法,但它只能返回一個字符串,並且您只能將結果賦給'k = str(mc)' – PRMoureu