【问题标题】:Python Namespace (Property) of inherited methods继承方法的 Python 命名空间(属性)
【发布时间】:2018-02-09 19:39:16
【问题描述】:

我想做的是使用某个命名空间访问继承的方法,例如:

class ExtraMeths(object):
    def specialmeth():
        pass

class MainClass(ExtraMeths):
    def standardmeth():
       pass
myclass = MainClass()
myclass.standardmeth()  #works
myclass.specialmeth()  #also works, but not ideal

现在理想情况下,我想做的是运行myclass.ExtraMeths.specialmeth(),其中ExtraMeths 的名称并不重要,但它位于主类自己的“属性”中。同样重要的是继承的类是继承的,即相同的 self 变量可供它使用。

原因是有很多方法,我想给它们一些顺序,所以将相似的方法组合在一起似乎是有道理的。

【问题讨论】:

  • 那么不要使用继承,使用composition

标签: python class inheritance properties


【解决方案1】:

这应该使用组合来完成:

class ExtraMeths(object):
    def __init__(self, main):
        self.main = main

    def specialmeth(self):
        # can use self.main here to access outer class variables

class MainClass(object):
    def __init__(self):
        self.extra_meths = ExtraMeths(self)

    def standardmeth(self):
        pass

myclass = MainClass()
myclass.standardmeth()
myclass.extra_meths.specialmeth()

【讨论】:

  • 非常酷-谢谢。有什么办法让它不必使用 self.main?
  • 如果ExtraMeths 不需要访问MainClass 实例上的任何内容即可完成工作,则您不需要self.main
  • 如问题中所述 - 如果 ExtraMeths 表现得像 MainClass 的继承类,即共享相同的自我,但可以通过组合访问,那将是理想的。
  • 此方法的垃圾收集也存在问题,如下所述(并已修复):stackoverflow.com/a/10791613/2356861
  • @RexFuzzle 这应该只是您计划实施__del__ 方法的问题,无论如何您可能不应该这样做......
猜你喜欢
  • 2013-03-10
  • 1970-01-01
  • 2017-02-06
  • 1970-01-01
  • 2013-08-13
  • 2017-12-10
  • 1970-01-01
  • 2014-07-29
  • 2014-12-28
相关资源
最近更新 更多