为了说明我的问题,这里有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 模块?
我希望我的问题很清楚,因为我真的很难将其正式化。
慕婉清6462132
相关分类