遵循 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 类方法的基类,它还删除不需要的关键字参数,如下所示。但是我想我需要从基类中引用派生类的 __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")
最佳答案
您已经引用了正确的类:cls
:
valid_kwargs = get_valid_kwargs(cls.__init__, config_dict)
类方法绑定(bind)到它被调用的类对象。对于 MyDerivedClass.from_yaml()
,cls
未绑定(bind)到父类,而是绑定(bind)到 MyDerivedClass
本身。
关于python - 如何从基类引用 Python 派生类的 __init__ 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20358931/