使用初始化父对象创建子类对象

时间:2016-04-15 13:39:59

标签: python inheritance

我有一个BaseEntity类,它定义了一堆(很多)非必需属性并具有大部分功能。我将这个类扩展为另外两个,它们有一些额外的方法,并初始化一个必需的属性。

class BaseEntity(object):

    def __init__(self, request_url):
        self.clearAllFilters()
        super(BaseEntity, self).__init__(request_url=request_url)

    @property
    def filter1(self):
        return self.filter1

    @filter1.setter
    def filter1(self, some_value):
        self.filter1 = some_value
    ...
    def clearAllFilters(self):
        self.filter1 = None
        self.filter2 = None
        ...

    def someCommonAction1(self):
        ...

class DefinedEntity1(BaseEntity):

    def __init__(self):
        super(BaseEntity, self).__init__(request_url="someUrl1")

    def foo():
        ...

class DefinedEntity2(BaseEntity):

    def __init__(self):
         super(ConsensusSequenceApi, self).__init__(request_url="someUrl2")

    def bar(self):
        ...

我想要的是初始化一次BaseEntity对象,指定所有过滤器,然后用它来创建每个DefinedEntities,即

baseObject = BaseEntity(None)
baseObject.filter1 = "boo"
baseObject.filter2 = "moo"

entity1 = baseObject.create(DefinedEntity1)

寻找pythonic的想法,因为我刚刚从静态类型的语言切换到仍然试图掌握python的力量。

1 个答案:

答案 0 :(得分:1)

一种方法:

import copy

class A(object):
    def __init__(self, sth, blah):
        self.sth = sth
        self.blah = blah

    def do_sth(self):
        print(self.sth, self.blah)

class B(A):
    def __init__(self, param):
        self.param = param

    def do_sth(self):
        print(self.param, self.sth, self.blah)

a = A("one", "two")
almost_b = copy.deepcopy(a)
almost_b.__class__ = B
B.__init__(almost_b, "three")
almost_b.do_sth() # it would print "three one two"

请记住,Python是一种非常开放的语言,具有很多动态修改的可能性,最好不要滥用它们。从干净的代码的角度来看,我只会使用一个普通的超级构造函数调用。