用继承抽象一个类

时间:2016-10-20 12:25:16

标签: python class inheritance

我仍然试图用Python包围类继承,所以请耐心等待:如果我有两个非常相似的类:

class Red:
    def print_color(self):
        print('red')

class Blue:
    def print_color(self):
        print('blue')

继承这些类以创建一个抽象类(比如说Color)的正确方法是什么,它使用某种确定哪个底层类被使用的参数进行初始化?初始化后,我应该可以这样做:

>>> a = Color('red')
>>> a.print_color()
red

3 个答案:

答案 0 :(得分:4)

To make that desired example work exactly as is, this is all you need:

class Color:
    def __init__(self, color):
        self.color = color

    def print_color(self):
        print(self.color)

No inheritance, nothing.

If you actually want Color('red') to result in an instance of the class Red, then Color just needs to be a factory function:

def Color(color):
    constructors = {'red': Red, 'blue': Blue}
    return constructors[color]()

Still no inheritance involved here.

答案 1 :(得分:1)

所以有很多可能的答案,但我认为一个非常好的答案称为工厂设计模式。它覆盖了很多不同的地方,但这里看起来很不错。

http://python-3-patterns-idioms-test.readthedocs.io/en/latest/Factory.html

答案 2 :(得分:0)

Inheritance makes sense when you have methods that need to be shared across all inheriting objects. Your example could be in that case:

class color(object):
    def __str__(self):
        return self.name

so when I inherit I could:

class red(color):
     def __init__(self):
         self.name = 'red'

and any time I print or convert a color to a string I would get the name I initialized ('red' in this case).

I want to note an important thing here if you're coming from common static (compiled) languages. __init__ is not the same as a regular constructor (is it really one at all?), so if I define within color:

class color(object):
    def __init__(self): 
        print 'Init color!'
    def __str__(self):
        return self.name

This would not get printed automatically when making a 'red' object, unless you explicitly call the base init (color.__init__(self) if you're interested).

This points brings me to re-defining inherited method (__init__ in my last example). Python uses override in this case, so the method defined by the (youngest) child is called unless an explicit call to a base method is made, ala:

base.some_method(child_object,...)

Just like with `__init__`. This somewhat shows the polymorphic nature of all python objects.

Those are the basics, just try and make some classes to get started.