代码之家  ›  专栏  ›  技术社区  ›  Roald

如何访问继承类的关键字参数默认值

  •  1
  • Roald  · 技术社区  · 6 年前

    我想对 seaborn.JointGrid 班我的计划是创建一个子类并从 JointGrid 类,例如:

    import seaborn
    
    class CustomJointGrid(seaborn.JointGrid):
    
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
    

    如果我这样做,我就无法访问变量 size ,则, ratio ,则, space 等,它们是 __init__ method of JointGrid :

    def __init__(self, x, y, data=None, size=6, ratio=5, space=.2,
    dropna=True, xlim=None, ylim=None) 
    

    我注意到这些变量没有在中初始化 连接网格 与往常一样上课 self.size = size __初始化__ 方法也许这就是为什么我不能从我的子类访问它们?

    如何访问这些变量 大小 ,则, 比率 ,则, 空间

    2 回复  |  直到 6 年前
        1
  •  3
  •   ekhumoro    6 年前

    您可以使用 inspect.getfullargspec 为此,请执行以下操作:

    >>> import seaborn, inspect
    >>> spec = inspect.getfullargspec(seaborn.JointGrid.__init__)
    >>> defaults = spec.kwonlydefaults or {}
    >>> defaults.update(zip(spec.args[-len(spec.defaults):], spec.defaults))
    >>> defaults
    {'data': None, 'size': 6, 'ratio': 5, 'space': 0.2, 'dropna': True, 'xlim': None, 'ylim': None}
    

    请注意,您的代码只需要这样做 一旦 ,因为导入类的签名不会更改。

        2
  •  1
  •   ImportanceOfBeingErnest    6 年前

    为什么不使用与要子类化的类相同的参数呢?

    import seaborn
    
    class CustomJointGrid(seaborn.JointGrid):
    
        def __init__(self, x, y, data=None, size=6, ratio=5, space=.2,
                     dropna=True, xlim=None, ylim=None, **kwargs):
            super().__init__(x, y, data=data, size=size, ratio=ratio, space=space,
                             dropna=dropna, xlim=xlim, ylim=ylim)
    

    否则你可以自己设置一些默认值,

    class CustomJointGrid(seaborn.JointGrid):
    
        def __init__(self, *args, **kwargs):
            size = kwargs.get("size", 6)
            kwargs.update(size=size)
            super().__init__(*args, **kwargs)
            # use size here
            self.someattribute = size*100