[英]How to access a Variable or list or dictionary inside a method of a class, outside the class?
[英]How to access a method inside a class?
環境:Python 2.7(可能相關)。
例如,我想根據是否已設置實例的屬性來調用類的原始__repr__
方法。
class A(object):
# original_repr = ?__repr__
def __init__(self, switch):
self.switch = switch
def __repr__(self):
if self.switch:
return self._repr()
else:
# return saved original __repr__ method.
def custom_repr(self):
pass
a = A()
a._repr = MethodType( custom_repr, a, A)
如何保存__repr__
方法?
顯然,我不能像實例那樣使用self
。
也不能使用A.__repr__
,因為那時A
本身尚未定義。
編輯:有人建議使用super().__repr__
,但是,我在代碼中對其進行了測試:
class C(object):
pass
class D(object):
def __repr__(self):
return super(self.__class__).__repr__()
c = C()
d = D()
# repr(c) --> '<__main__.C object at 0x0000000003AEFBE0>'
# repr(d) --> "<super: <class 'D'>, NULL>"
您會看到super().__repr__
與原始__repr__
我想你在找
super().__repr__()
class A:
# original_repr = ?__repr__
def __init__(self, switch):
self.switch = switch
def __repr__(self):
return super().__repr__()
def __repr__(self):
if self.switch:
return "Hello"
return super().__repr__()
您可以通過super().__repr__()
退回到超類的__repr__
方法。 下面將通過子類化一個新類來顯示一個示例。
因此,如果我們有一個如下的父class B
,並定義了自己的__repr__
class B:
def __repr__(self):
return 'This is repr of B'
然后我們像以前一樣有一個子class A
,它從B
繼承,它可以按如下所示回__repr__
B的__repr__
class A(B):
def __init__(self, switch):
super().__init__()
self.switch = switch
def __repr__(self):
#If switch is True, return repr of A
if self.switch:
return 'This is repr of A'
#Else return repr of B by calling super
else:
return super().__repr__()
您可以通過以下方式進行測試
print(A(True))
print(A(False))
不出所料,第一種情況將觸發A的__repr__
,第二種情況將觸發B的__repr__
。
This is repr of A
This is repr of B
如果A只是從對象繼承的普通類,則代碼將更改為
class A:
def __init__(self, switch):
super().__init__()
self.switch = switch
def __repr__(self):
#If switch is True, return repr of A
if self.switch:
return 'This is repr of A'
#Else return repr of superclass by calling super
else:
return super().__repr__()
然后輸出將變為
print(A(True))
#This is repr of A
print(A(False))
#<__main__.A object at 0x103075908>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.