在python中访问父方法
我有两个文件,在python中访问父方法,python,class,inheritance,methods,Python,Class,Inheritance,Methods,我有两个文件,main.py和ColorPoint.py。最后一个由继承自Point类的Point类和ColorPoint类组成。有没有办法从main.py文件访问Point的方法 例如,我在Point和ColorPoint类中有两种方法\uuuu str\uuu。但是我想将colorpoint对象打印为Point: print colorpoint # gives output from Point class, not ColorPoint class 我知道如何通过super从类访问父方
main.py
和ColorPoint.py
。最后一个由继承自Point
类的Point
类和ColorPoint
类组成。有没有办法从main.py
文件访问Point
的方法
例如,我在Point
和ColorPoint
类中有两种方法\uuuu str\uuu
。但是我想将colorpoint
对象打印为Point
:
print colorpoint # gives output from Point class, not ColorPoint class
我知道如何通过super
从类访问父方法,但如何从main
而不是从类访问父方法?您正在寻找的
在python中,当您通过类调用方法时,“self”不会自动绑定(它如何知道在哪个实例上操作?),您必须自己传递它。“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"
为了完全满足您的规范,您还可以找到在运行时以编程方式调用哪些方法的父类,例如这样的父类(不安全的实现,仅用于教育目的,将破坏更复杂的设置,不要在生产中使用类似的东西,这是可怕的代码,免责声明):
这是一个不寻常的请求-你能提供一些关于你想要达到的目标的更多信息吗,也许有更好的方法来达到你想要达到的目标…
Point.\uu str\uuuu(colorpoint)
?Rusty,是的-正是我想要的!!!如果您想要父类的\uuuu str\uuuu
实现,为什么要在子类上实现它呢?@ovod嗯,您可能不应该使用这种类型的东西。你应该重新考虑你的设计,这是一种肮脏的黑客代码。
>>> b.__class__.__base__.__repr__(b)
"I'm A's __repr__ operating on a B"