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

标签 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 类方法的基类,它还删除不需要的关键字参数,如下所示。但是我想我需要从基类中引用派生类的 __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/

相关文章:

java - 具有持久性的实体类中的 Id 与引用

javascript - javascript 中具有同名的 getter 和函数

c# - 子类需要基类中的属性信息

c++ - 继承重载函数 : Requires namespace?

python - 通过日志记录更新 QTextEdit 时 PyQt5 程序崩溃

python - 成功的 cv2.calibrateCamera 后如何获得良好的 cv2.stereoCalibrate

oop - 我可以在许多从属设备上使用相同的 Jenkins 作业名称(即多态)吗?

c++ - 无效的协变返回类型错误

python - 用于匹配 "01.0 to 60.0 in steps of 0.5, or 99.9"的正则表达式?

python - 抓取时获取错误实例方法没有属性 '__getitem__'