简体   繁体   English

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

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

I have a base class that is inherited by multiple child classes. 我有一个由多个子类继承的基类。 This base class has a method, calc_func(self), which uses uniformly named methods, func(self), in the child classes. 这个基类有一个方法calc_func(self),它在子类中使用统一命名的方法func(self)。 This works but this 'architecture' would be very hard to follow if the code ever grew more complex. 这可行,但如果代码变得越来越复杂,这个“架构”将很难遵循。

# 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

The idea was to abstract out common code to the base class but this doesn't seem to be the right way of doing it. 我们的想法是将公共代码抽象出基类,但这似乎不是正确的方法。 Maybe this could be made more understandable by using a naming convention for methods and attributes which reference their particular class of origin? 也许通过使用引用其特定原始类的方法和属性的命名约定,可以使这更容易理解? Maybe a different architecture altogether? 也许完全不同的架构? Any advise will be greatly appreciated. 任何建议将不胜感激。

This base class has a method, calc_func(self), which uses uniformly named methods, func(self), in the child classes. 这个基类有一个方法calc_func(self),它在子类中使用统一命名的方法func(self)。 This works but this 'architecture' would be very hard to follow if the code ever grew more complex. 这可行,但如果代码变得越来越复杂,这个“架构”将很难遵循。

No, that's exactly how object-oriented polymorphism is supposed to work. 不,这正是面向对象的多态性应该如何工作的。 You're already doing it right! 你已经做对了!

You say that this seems difficult to understand, but it's not clear why you think it's difficult. 你说这似乎很难理解,但不清楚为什么你认为这很困难。 Probably the only thing you could do is (a) mark the base class as abstract (b) have all methods that child classes are supposed to supply exist on the base class, but only have them raise NotImplementedError . 可能你唯一能做的就是(a)将基类标记为抽象 (b)将子类应该提供的所有方法都存在于基类中,但只有它们引发NotImplementedError

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

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