无论如何,是否可以覆盖其他模块中的类,同时将其方法保留在 python 中

为了说明我的问题,这里有3个模块:


这是模块A


'''

lets call this module the parent, it regroups multiple classes with several

method each

'''


class Rectangle():

    '''

    The basic rectangle class that is parent for other classes in this

    module

    '''

    def __init__(self, x_length, y_length):

        self.x_length = x_length

        self.y_length = y_length


    def create_points(self):

        '''

        Basic geometrical method 

        '''

        self.point_1 = [x_length/2, y_length/2]

        self.point_2 = [-x_length/2, y_length/2]

        self.point_3 = [-x_length/2, -y_length/2]

        self.point_4 = [x_length/2, -y_length/2]


class Square(Rectangle):

    '''

    The square that is a rectangle with two identical sides

    '''

    def __init__(self, side_dim):

        super().__init__(side_dim, side_dim)


class SquareCollection():

    '''

    Creates a composition relation with an other class of the module

    '''

    def __init__(self, dim_list):

        '''

        The constructor creates a square for every float in the given list

        '''

        for val in dim_list:

            try:

                self.element.append(Square(val))

            except AttributeError:

                self.element = [Square(val)]


    def create_points(self):

        for elmt in self.element:

            elmt.create_points()

当我导入模块 B2 创建一个sc = SquareCollection([4, 3.5, 0.8])实例然后运行时sc.module_specific_method(),我得到一个使用 A 模块创建的被AttributeError调用类的实例,因为该类继承自 A 模块中定义的类,而 A 模块本身根据 A 模块中定义的类创建多个实例相同的模块。这是预期的,因为我在 A 模块中没有定义 this 。SquareSquareCollectionSquareAttributeErrormodule_specific_method


由于我的代码结构以及我当前的使用方式,我使用模块 B1 或模块 B2。目前,我通过重写模块 A 中包含的所有内容两次(一次在 B1 中,另一次在 B2 中)来避免此问题。因为我正在重构所有代码,所以我希望可以删除所有重复代码并将其放入“通用”模块中,如上面的简化示例所示。


模块 A 中的类如何继承/指向我调用它的 B 模块?


我希望我的问题很清楚,因为我真的很难将其正式化。


拉丁的传说
浏览 110回答 1
1回答

慕婉清6462132

Square您可以通过将基类中使用的类作为SquareCollection集合类的属性来实现此目的,这样子类也可以显式覆盖它,而不是进行硬编码:# Module_Aclass Square:    pass      # implement stuff hereclass SquareCollection    BaseItem = Square    # the "class that is collected here"    def __init__(self, dim_list):        # spawn BaseItem instances here, which are Square by default,        # but might be set to something else in a subclass        self.element = [self.BaseItem(val) for val in dim_list]# Module_B1import Module_A as maclass Square(ma.Square):     passclass SquareCollection(ma.SquareCollection):    # override the collection's BaseItem with this module's Square class,    # but keep the rest of the SquareCollection code the same    BaseItem = Square    
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python