📜  Python中的条件继承

📅  最后修改于: 2022-05-13 01:55:42.987000             🧑  作者: Mango

Python中的条件继承

大多数情况下,我们需要决定一个特定的类是否应该继承一个类,例如给定一个人,如果他/她有资格被大学录取,那么他们应该是学生否则他们不应该是学生。

让我们考虑一个示例,在给定条件的情况下,我们希望一个类(例如 C)动态地从类 A 或类 B 继承。我们需要创建两个不同的类 C_A 和 C_B,它们分别从 A 和 B 继承,但是如果条件继承是基于条件继承或不继承,那么我们可以使用下面讨论的不同方法

示例 1:2 个类之间的条件继承:

创建两个类 C_A 和 C_B,并根据条件返回各自的类对象。

Python3
class A(object): 
    def __init__(self, x): 
        self.x = x
      
    def getX(self): 
        return self.X
    
class B(object): 
    def __init__(self, x, y): 
        self.x = x
        self.y = y
    def getSum(self): 
        return self.X + self.y
  
# inherits from A  
class C_A(A):
    def isA(self):
        return True
      
    def isB(self):
        return False
  
# inherits from B  
class C_B(B):
    def isA(self):
        return False
    
    def isB(self):
        return True
  
# return required Object of C based on cond  
def getC(cond):
    if cond:
        return C_A(1)
    else:
        return C_B(1,2)
  
# Object of C_A
ca = getC(True)
print(ca.isA())
print(ca.isB())  
    
# Object of C_B  
cb = getC(False)
print(cb.isA())
print(cb.isB())


Python3
class A(object): 
    def __init__(self, x): 
        self.x = x
      
    def getX(self): 
        return self.X
  
# Based on condition C inherits 
# from A or it inherits from 
# object i.e. does not inherit A
cond = True  
  
# inherits from A or B
class C(A if cond else object):
    def isA(self):
        return True
  
# Object of C_A
ca = C(1)
print(ca.isA())


Python3
class A(object): 
    def __init__(self, x): 
        self.x = x
      
    def getX(self): 
        return self.X
  
# Based on condition C inherits from
# A or it inherits from object i.e.
# does not inherit A
cond = False
  
## inherits from A or B
class C(A if cond else object):
    def isA(self):
        return True
  
# Object of C_A
ca = C(1)
print(ca.isA())


输出:

True
False
False
True

示例 2:对于是否从 A 继承或不继承:

方法是在声明给定类 C 继承的类时使用条件语句。下面的代码执行并返回 True

Python3

class A(object): 
    def __init__(self, x): 
        self.x = x
      
    def getX(self): 
        return self.X
  
# Based on condition C inherits 
# from A or it inherits from 
# object i.e. does not inherit A
cond = True  
  
# inherits from A or B
class C(A if cond else object):
    def isA(self):
        return True
  
# Object of C_A
ca = C(1)
print(ca.isA())

输出:

True

示例 3:以下代码不会运行,因为 C 不继承自 A,因此具有不带任何参数的默认构造函数

Python3

class A(object): 
    def __init__(self, x): 
        self.x = x
      
    def getX(self): 
        return self.X
  
# Based on condition C inherits from
# A or it inherits from object i.e.
# does not inherit A
cond = False
  
## inherits from A or B
class C(A if cond else object):
    def isA(self):
        return True
  
# Object of C_A
ca = C(1)
print(ca.isA())

输出: