2014-11-24 64 views
-1

我有两个文件,main.pyColorPoint.py。最后一个由Point类和ColorPoint类组成,继承自Point类。有没有办法从main.py文件中访问Point的方法?在Python中访问父级方法

例如我有两种方法__str__PointColorPoint类。但我想打印colorpoint对象只是Point

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

我知道如何从类通过super访问父方法,但如何从main这样做,不来上课?

+5

这是一个不寻常的请求 - 您能不能给一些更多的信息n对你想要达到的目标,也许有更好的方法去尝试...... – 2014-11-24 13:54:59

+0

'Point .__ str __(colorpoint)'? – Rusty 2014-11-24 13:55:21

+0

生锈,是的 - 正是我想要的! – ovod 2014-11-24 13:57:34

回答

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" 

而且能充分满足您的规格,你也可以找出父类在运行时编程调用哪些方法,例如像这样(不是一个安全的实现,仅用于教育目的,将打破更多复杂的设置,请不要使用sometig这样的生产,这是可怕的代码,disclaimerdisclaimerdisclaimer)

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