类方法作为构造函数和继承 [英] classmethod as constructor and inheritance

查看:93
本文介绍了类方法作为构造函数和继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题很简单。如果类 B 继承类 A 并想覆盖用作构造函数的 classmethod(我猜您称其为工厂方法)。问题是 B.classmethod 将要重用 A.classmethod ,但是随后必须创建一个实例类A的子类,而它却是类A的子类-因为作为类方法,它没有自我。 然后,这似乎并不是设计它的正确方法。

The problem is quite simple. If a class B inherit a class A and wants to override a ´classmethod´ that is used as a constructor (I guess you call that a "factory method"). The problem is that B.classmethod will want to reuse A.classmethod, but then it will have to create an instance of the class A, while it subclasses the class A - since, as a classmethod, it has no self. And then, it doesn't seem the right way to design that.

我做了一个琐碎的示例,通过阅读,我做的事情更加复杂numpy数组等。但是我想这里没有信息丢失。

I did the example trivial, I do more complicate stuff by reading numpy arrays, etc. But I guess there is no loss of information here.

class A:
    def __init__(self, a):
        self.el1 = a

    @classmethod
    def from_csv(cls, csv_file):
        a = read_csv(csv_file) 
        return cls(a)

    @classmethod
    def from_hdf5 ...

class B(A):
    def __init__(self, a, b)
        A.(self, a)
        self.el2 = b

    @classmethod
    def from_csv(cls, csv_file):
        A_ = A.from_csv(csv_file) #instance of A created in B(A)
        b = [a_*2 for a_ in A.el]
        return cls(A.el, b) 

是否有Python方式来处理?

Is there a pythonic way to deal with that?

推荐答案

进行了一些不同的尝试之后。我的结论是,您应该重写 classmethod 而不重用内部代码。因此,对于我的特定问题,我发现的最佳方法是使 classmethod 尽可能简单,然后将要重用的代码放入另一种方法 static 就我而言,因为类方法是构造函数。

After doing some different trials. My conclusion is that you should override a classmethod without reusing the code inside. So the best way I found, for my particular problem, is to make the classmethod as simply as possible and put the code I want to reuse in another method, static in my case, since the classmethod is a constructor.

这篇关于类方法作为构造函数和继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆