![](/img/trans.png)
[英]How to access class member functions from within different instances of that same class? Python
[英]How can I access a class data member from a method within the same class?
class Class:
_member = 1
def method(self):
我想從method()
內部訪問_member
,這樣做的正確方法是什么?
class Class:
_member = 1
@classmethod
def method(cls):
print cls._member
Class.method()
和:
>>> Class().method()
1
>>>
您可以使用self._member
,如果它不是對象的屬性(在self.__dict__
),我相信它會在接下來的__dict__
類中查找,該類應包含類屬性。
class Class:
_member = 1
def method(self):
print "value is ",self._member
創建類的實例並調用方法
c = Class()
c.method()
輸出:
value is 1
class Class:
_member = 1
def method(self):
print(Class._member)
Class().method()
將給出輸出:
1
順便說一句,那是一個Class屬性。 您可以將該方法稱為綁定方法。 您可以選擇使用staticmethod(不需要第一個參數),classmethod(第一個參數是一個類)和普通方法(像這樣)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.