【问题标题】:access parent methods in python在python中访问父方法
【发布时间】:2014-11-24 13:52:15
【问题描述】:

我有两个文件,main.pyColorPoint.py。最后一个由Point 类和继承自Point 类的ColorPoint 类组成。有什么方法可以从main.py 文件中访问Point 的方法吗?

例如,我在PointColorPoint 类中有两个方法__str__。但我想将colorpoint 对象打印为Point

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

我知道如何通过super 从类中访问父方法,但是如何从main 而不是从类中做同样的事情?

【问题讨论】:

  • 这是一个不寻常的请求 - 你能否提供更多关于你想要实现的目标的信息,也许有更好的方法来实现你正在尝试的目标......
  • Point.__str__(colorpoint) ?
  • 生锈,是的——正是我想要的!!!
  • 如果你想要父类的__str__实现,为什么要在子类上实现呢?
  • @ovod 好吧,您可能不应该使用这种类型的东西。你应该重新考虑你的设计,这是一种肮脏的代码。

标签: python class inheritance methods


【解决方案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,这是可怕的代码,免责声明disclaimerdisclaimer)

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

【讨论】:

    猜你喜欢
    • 2011-06-16
    • 1970-01-01
    • 2021-01-11
    • 1970-01-01
    • 2020-12-21
    • 2011-06-09
    • 1970-01-01
    • 2016-01-16
    • 1970-01-01
    相关资源
    最近更新 更多