访问python中的父方法

时间:2014-11-24 13:52:16

标签: python class inheritance methods

我有两个文件,main.pyColorPoint.py。最后一个包含从Point类继承的ColorPoint类和Point类。有没有办法从Point文件中访问main.py的方法?

例如,我在__str__Point类中有两种方法ColorPoint。但我想将colorpoint对象打印为Point

print colorpoint # gives output from Point class, not ColorPoint class

我知道如何通过super从类访问父方法,但是如何从main而不是从类中执行相同操作?

1 个答案:

答案 0 :(得分:1)

您正在寻找the thingy formerly known as unbound methods

在python中,当你通过类调用一个方法时," self"不会自动绑定(如何知道要在哪个实例上运行?),你必须自己传递它。那个"自我"不必是该类的实际实例。

所以你可以这样做:

>>> class A(object):
...   def __repr__(self):
...      return "I'm A's __repr__ operating on a " + self.__class__.__name__
... 
>>> class B(A):
...   def __repr__(self):
...      return "I'm B's __repr__"
... 
>>> b=B()
>>> b
I'm B's __repr__
>>> A.__repr__(b)
"I'm A's __repr__ operating on a B"

为了完全符合您的规范,您还可以找到父类在运行时以编程方式调用哪些方法,例如像(不是安全的实现,仅出于教育目的,将在更复杂的设置中中断,不要在制作中使用像这样的像这样,这是可怕的代码,disclaimerdisclaimerdisclaimer)

>>> b.__class__.__base__.__repr__(b)
"I'm A's __repr__ operating on a B"