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

2024-06-02 06:50:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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对象一次,指定所有的过滤器,然后使用它来创建每个definedEntity,即

^{pr2}$

正在寻找python思想,因为我刚刚从静态类型化语言转换过来,仍然试图掌握python的强大功能。在


Tags: self功能noneurl属性initvaluerequest
1条回答
网友
1楼 · 发布于 2024-06-02 06:50:57

一种方法:

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是一种非常开放的语言,有很多动态修改的可能性,最好不要滥用它们。从干净代码的角度来看,我将使用一个简单的旧调用来调用superconstructor。在

相关问题 更多 >