【问题标题】:Call __call__ method from both parents classes从两个父类调用 __call__ 方法
【发布时间】:2020-10-02 11:13:06
【问题描述】:

我有课:

class C1():
    def __call__(self,name='1'):
        self.name=name
        print(self.name)

class C2():
    def __call__(self,name='2'):
        self.name=name
        print(self.name)

class C3(C1, C2):
    def __call__(self,name='=>35'):
        super().__call__()
        self.name=name
        print(self.name)

结果:

1
=>35

但我所期望的:

1
2
=>35

如何从两个父类调用这个方法?

【问题讨论】:

    标签: python-3.x class oop


    【解决方案1】:

    super() 只是获取方法解析顺序中的下一个或“mro”。 它不会神奇地一次调用多个方法。

    通常您会在每个班级中拨打super() 电话。这样它总是会自行解决。在这种情况下,最后一行将引发AttributeError

    但是,您可以通过检查您的方法是否具有您尝试在父类中调用的方法来解决此问题。

    class C1():
        def __call__(self,name='1'):
            self.name=name
            print(self.name)
            # I'm sure ther is a more pythonic way to do this
            # but this just checks if your super class has a
            # call method before calling it
            # you could just try catch the AttributeError as well
            # either way, your IDE will probably complain about this.
            super_class = super()
            if hasattr(super_class, '__call__'):
                super_class.__call__()
    
    class C2():
        def __call__(self,name='2'):
            self.name=name
            print(self.name)
            super_class = super()
            if hasattr(super_class, '__call__'):
                super_class.__call__()
    
    class C3(C1, C2):
        def __call__(self,name='=>35'):
            super().__call__()
            self.name=name
            print(self.name)
    
    foo = C3()
    foo()
    

    【讨论】:

      猜你喜欢
      • 2011-12-10
      • 2012-09-02
      • 2020-07-22
      • 1970-01-01
      • 1970-01-01
      • 2017-11-09
      • 2012-02-22
      • 1970-01-01
      • 2017-10-25
      相关资源
      最近更新 更多