仅在存在的情况下如何扩展类

时间:2019-06-19 01:06:20

标签: python python-3.x inheritance try-catch

我正在从样式表中构建一些代码,但我也希望能够在python中添加自定义类。但是,有时,自定义类将不存在。例如,我有两个类:foo_basefoo_custom。我想定义一个可以扩展两个类的类foo,如果不存在foo_base则只能扩展foo_custom

try:
    def foo(foo_base, foo_custom):
except:
    def foo(foo_base):
...
        def __init__(self):
            ...

希望这是有道理的。本质上,我想扩展该类(如果存在)。

谢谢!

2 个答案:

答案 0 :(得分:0)

类型构造函数中的父类参数(即class语句)不是使用某种类型的异常来处理两种情况,而是允许在Python 3中扩展列表的参数。例如:

parent_classes = [MainParent]

# it is also possible to make use of `importlib` to go through a
# list of possible imports rather than doing this one-by-one in
# this verbose manner
try:
    from might_be_missing import SomeOtherClass
except ImportError:
    pass  # perhaps log a warning of some kind
else:
    parent_classes.append(SomeOtherClass)

# To create the class

class YourClass(*parent_classes):
    """
    The main class definition
    """

但是,对于特定的最终用户而言,这种特定模式通常不是有用的模式,因为这不能提供一个稳定的行为,用户可以轻易推断出这种行为,因为它被卡在了他们可能不愿意使用的系统后面一定有控制权。对于类class composition来说,一种更有用的关于类继承的技术是problem you might be actually solving

另请参阅:Python: Inheritance versus Composition

答案 1 :(得分:0)

您可以使用注册表来注册您的类,然后检查注册表以查看其是否存在。

class Registry(): #Creating Registry class

   def __init__(self):
      self.registry = []

   def register(self,class_):
      self.registry.append(class_) 
      return class_

   def check(self, class_):
       if class_ in self.registry:
           return True

registry = Registry()  #Creating Registry object

@registry.register  #Adding to the Registry
class Some():
     pass
Some()  #Creating class instance
print(registry.check(Some))  #Checking if it exists
#Output
#True

然后只需致电

if registry.check(your_class):
   #Do something```
相关问题