gpt4 book ai didi

python - 元编程 - 使用 __class__ 时如何从模板生成类?

转载 作者:行者123 更新时间:2023-12-01 06:45:19 26 4
gpt4 key购买 nike

我创建了这样的类来解决签名和 feature_names 的问题:

import copy
from sklearn.feature_selection import VarianceTreshold


class VarianceThresholdN(VarianceThreshold):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.feature_names = None

#hack from https://stackoverflow.com/questions/51430484/how-to-subclass-a-vectorizer-in-scikit-learn-without-repeating-all-parameters-in
def get_params(self, deep=True):
params = super().get_params(deep)
cp = copy.copy(self)
cp.__class__ = VarianceThreshold
params.update(cp.__class__.get_params(cp, deep))
return params

def fit(self, X, y=None):
self.feature_names = list(X.columns)
return super().fit(X, y)

不幸的是,我需要创建很多这样的类,所以需要进行大量的复制粘贴和替换两件事:class VarianceThresholdN(VarianceThreshold):class DifferentClassN(DifferentClass):cp.__class__ = VarianceThresholdcp.__class__ = DifferentClass

所以有一个清晰的模板,但由于 cp.__class__ = ... 我无法使用 mix-ins。

也许这个代码可以用 jinja 模板生成,但是有没有办法通过元编程的一些 Python 技巧来避免它?

最佳答案

我真的不明白它应该做什么,据我所知,你几乎只是调用了 super() 两次,第二个版本明确地这样做了。

Probably this code could be generated with jinja templates, but is there any way to avoid it, with some pythonic trick from meta-programming?

如果您的模式是您总是想将 self.__class__ 与其父级“交换”,则可以使用 __bases__mro( )[1]:

  • cls.__bases__cls 的所有父类(super class)的元组,它正是您放在括号中的内容(不包括 kwargs)
  • cls.mro() 是“方法解析顺序”,它对于这种特定的(完全线性)情况可以很好地工作:它是处理属性或处理时要经过的所有类的序列。方法调用,从cls(包含)开始,到object(这是所有Python类的原始祖先)结束。

关于python - 元编程 - 使用 __class__ 时如何从模板生成类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59248211/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com