如何从基类中引用Python中派生类的__init__方法?

时间:2013-12-03 18:32:19

标签: python oop inheritance yaml class-method

遵循SO问题What is a clean, pythonic way to have multiple constructors in Python?Can you list the keyword arguments a Python function receives?我想创建一个具有from_yaml classmethod的基类,并且还删除不需要的关键字args,如下所示。但我认为我需要从基类引用派生类的__init__方法。我如何在Python中执行此操作?

def get_valid_kwargs(func, args_dict):
    valid_args = func.func_code.co_varnames[:func.func_code.co_argcount]
    kwargs_len = len(func.func_defaults)  # number of keyword arguments
    valid_kwargs = valid_args[-kwargs_len:]  # because kwargs are last
    return dict((key, value) for key, value in args_dict.iteritems()
                if key in valid_kwargs)


class YamlConstructableClass(object):
    @classmethod
    def from_yaml(cls, yaml_filename):
        file_handle = open(yaml_filename, "r")
        config_dict = yaml.load(file_handle)
        valid_kwargs = get_valid_kwargs(AnyDerivedClass.__init__, config_dict)  # I don't know the right way to do this
        return cls(**valid_kwargs)


class MyDerivedClass(YamlConstructableClass):
    def __init__(self, some_arg, other_arg):
        do_stuff(some_arg)
        self.other_arg = other_arg

derived_class = MyDerivedClass.from_yaml("my_yaml_file.yaml")

1 个答案:

答案 0 :(得分:4)

您已经引用了正确的类:cls

valid_kwargs = get_valid_kwargs(cls.__init__, config_dict)

类方法绑定到要调用的类对象。对于MyDerivedClass.from_yaml()cls未绑定到父类,而是绑定到MyDerivedClass本身。