【发布时间】:2019-09-25 01:41:45
【问题描述】:
我定义了以下类:
class First(object):
def __init__(self):
print("first")
def mF1(self):
print "first 1"
def mF2(self):
print "first 2"
class Second(object):
def __init__(self):
print("second")
def mS1(self):
print "second 1"
class Third(object):
def __init__(self):
print("third")
def mT1(self):
print "third 1"
def mT2(self):
print "third 2"
def mT3(self):
print "third 3"
class Fourth(First, Second, Third):
def __init__(self):
super(Fourth, self).__init__()
print("fourth")
C = Fourth()
C.mF1()
C.mF2()
C.mS1()
C.mT1()
C.mT2()
C.mT3()
它给出了输出:
first
fourth
first 1
first 2
second 1
third 1
third 2
third 3
这样,很明显First、Second、Third 和Fourth 类的所有属性和方法都在类Fourth 中可用。
现在,我希望 Fourth 类根据上下文选择性地从父级继承 - 即单独从 First 或从 First 和 Third 等。一种方法是定义如下的单独类:
class Fourth1(First):
def __init__(self):
super(Fourth, self).__init__()
print("fourth first")
class Fourth2(First, Third):
def __init__(self):
super(Fourth, self).__init__()
print("fourth first third")
这意味着定义了单独的类,并且具有单独的类名而不是一个。
我想知道是否有更简单、动态和“pythonic”的方式来实现这一点?是否可以以简单的方式选择从哪里继承(就像super() 所做的那样,继承所有属性和方法,包括私有方法),比如,
C = Fourth(1,0,0)
从First和
C = Fourth(1,0,1)
从First 和Third 继承?
【问题讨论】:
-
从所有类继承的类不适合你的需要,就像只从一两个继承的类吗?或者换句话说:if it quacks like a duck, it is a duck。如果它也能吠叫有什么关系?
-
@KlausD。我明白你的意思。但是如果代码库很大,有很多不需要的东西可能会给系统资源造成负担,不是吗?
-
仅当您从那些“不需要的”类中运行代码时。
-
注明。这很有启发性。
标签: python python-2.7 class inheritance multiple-inheritance