在python中保留其他模块的方法的同时,是否还可以重写其他模块中的类

2024-10-03 11:16:46 发布

您现在位置: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()

这是B1模块

'''
lets call this module the child 1, it redefines the classes from the parent but
with an additionnal method specific for its use case
'''
import Module_A as ma

class Rectangle(ma.Rectangle):
    '''
    The basic rectangle class that is parent for other classes in this
    module
    '''
    def module_specific_method(self):
        self.special_attribute_1 = True

class Square(ma.Square):
    '''
    The square that is a rectangle with two identical sides
    '''
    def module_specific_method(self):
        self.special_attribute_1 = True

class SquareCollection(ma.SquareCollection):
    '''
    Redefining the SquareCollection with an additionnal method
    '''
    def module_specific_method(self):
        for elmt in self.element:
            elmt.module_specific_method()

这是模块B2

'''
lets call this module the child 2, it redefines the classes from the parent but
with an additionnal method specific for its use case
This module is a copy of Module_B2 and is used to justify the used code
structure
'''
import Module_A as ma

class Rectangle(ma.Rectangle):
    '''
    The basic rectangle class that is parent for other classes in this
    module
    '''
    def module_specific_method(self):
        self.special_attribute_2 = True

class Square(ma.Square):
    '''
    The square that is a rectangle with two identical sides
    '''
    def module_specific_method(self):
        self.special_attribute_2 = True

class SquareCollection(ma.SquareCollection):
    '''
    Redefining the SquareCollection with an additionnal method
    '''
    def module_specific_method(self):
        for elmt in self.element:
            elmt.module_specific_method()

当我导入模块B2时,创建一个sc = SquareCollection([4, 3.5, 0.8])实例,然后运行sc.module_specific_method(),我得到一个被调用的Square类的AttributeError,这些类是使用a模块创建的,因为SquareCollection类继承了a模块中定义的一个实例,而a模块本身基于同一模块中定义的类创建了多个Square实例。需要AttributeError,因为在A模块中我没有定义这个module_specific_method

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

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

我希望我的问题是明确的,因为我真的很难把它正式化

干杯


Tags: 模块theinselfforisdefwith
1条回答
网友
1楼 · 发布于 2024-10-03 11:16:46

您可以通过将基类SquareCollection中使用的Square类作为集合类的属性来实现这一点,这样它就不再是硬编码的,而是可以被子类显式重写:

# Module_A
class Square:
    pass      # implement stuff here

class 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_B1
import Module_A as ma

class Square(ma.Square):
     pass

class 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    

相关问题 更多 >