繁体   English   中英

Python,引用基类中的子属性和方法(反之亦然)必须有更好的方法

[英]Python, Referencing child attributes and methods in base class (and vice versa) there has to be a better way

我有一个由多个子类继承的基类。 这个基类有一个方法calc_func(self),它在子类中使用统一命名的方法func(self)。 这可行,但如果代码变得越来越复杂,这个“架构”将很难遵循。

# Base class
class base():
    x = 12  
    def calc_func(self):
        for i in range(1,4):
            self.y += self.func() 
            # neither y nor func() are defined here so
            # it is hard to know where they came from


# Child class 1
class child1(base):
    y = 10
    def __init__(self):
        pass

    def func(self):   # method used in base class
        self.x += self.y
        print self.x
        return self.x
        # x was not defined here so it is
        # hard to know where it came from

# Child class 2
class child2(base):
    y = 15
    def __init__(self):
        pass

    def func(self):   # method used in base class
        self.x *= self.y
        print self.x
        return self.x
        # x was not defined here so it is
        # hard to know where it came from

test1 = child1()  # Create object
test1.calc_func() # Run method inherited from base class


test2 = child2()  # Create another object
test2.calc_func() # Run method inherited from base class

我们的想法是将公共代码抽象出基类,但这似乎不是正确的方法。 也许通过使用引用其特定原始类的方法和属性的命名约定,可以使这更容易理解? 也许完全不同的架构? 任何建议将不胜感激。

这个基类有一个方法calc_func(self),它在子类中使用统一命名的方法func(self)。 这可行,但如果代码变得越来越复杂,这个“架构”将很难遵循。

不,这正是面向对象的多态性应该如何工作的。 你已经做对了!

你说这似乎很难理解,但不清楚为什么你认为这很困难。 可能你唯一能做的就是(a)将基类标记为抽象 (b)将子类应该提供的所有方法都存在于基类中,但只有它们引发NotImplementedError

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM