![](/img/trans.png)
[英]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.