亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

無論如何,是否可以覆蓋其他模塊中的類,同時將其方法保留在 python 中

無論如何,是否可以覆蓋其他模塊中的類,同時將其方法保留在 python 中

拉丁的傳說 2023-06-27 14:22:51
為了說明我的問題,這里有3個模塊:這是模塊A'''lets call this module the parent, it regroups multiple classes with severalmethod 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 模塊?我希望我的問題很清楚,因為我真的很難將其正式化。
查看完整描述

1 回答

?
慕婉清6462132

TA貢獻1804條經驗 獲得超2個贊

Square您可以通過將基類中使用的類作為SquareCollection集合類的屬性來實現此目的,這樣子類也可以顯式覆蓋它,而不是進行硬編碼:


# 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    


查看完整回答
反對 回復 2023-06-27
  • 1 回答
  • 0 關注
  • 126 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號