簡體   English   中英

在 OOP Python ZE5BA8B4C539C287BAAAEZ34

[英]What is the best way to use one function with same parameters in multiple classes in OOP Python tkinter

我試圖弄清楚如何制作與兩個類兼容的 function。 我有兩個類的參數與另一個類完全相同,每個類都有更多參數。 而且我需要使用兩個類中完全相同的 function。 有沒有一種方法可以使用 function 而只挑戰一次?

為了更清楚,這是我的情況。 我有一個帶有表單Tkinter應用程序。 表單本身是 class ,但我也有一個 class ,它顯示來自但默認填充和禁用的表單作為關於注冊人的詳細信息的顯示。 單擊按鈕后,您可以更改該表單中的數據並在數據庫中更新它。 因為這兩個類非常相似,所以我使用命名和 class 形式的所有內容來構建人員詳細信息 class。 但在這里我想調用驗證 function。 提交和更新數據時將調用相同的 function。 在每個 class 中,它只需要self參數,但我不知道如何只定義一次並在兩個類中使用它

在 python 和許多其他編程語言中一樣,您可以創建子類,這些子類可以繼承父 class 的一些屬性(參數)和方法(函數)。 對於某些類共享相同元素的情況,Object 面向編程的最佳實踐是創建一個父 class,它由您的兩個子類繼承,通過這樣做,您可以向它們傳遞不同的參數,但只編寫一次代碼。

class parent:
    def __init__(self, first, second):
        self.first = first
        self.second = second

    def shared_method(self, *some_parameters):
        # This method is doing something useful
        pass


# by putting some class name in brackets you are inheriting all from that class
class child1(parent):

    def __init__(self, first, second, third):
        # keyword super lets you avoid referring to the base class explicitly and takes for you everything that is already in parent's __init__
        super().__init__(first, second)
        self.third = third  # and you can than define new attributes specific to that class


class child2(parent):

    def __init__(self, first, second):
        super().__init__(first, second)

    def new(self, x):
        pass

您接下來可以研究的一些高級內容是:如何創建抽象類,以便您只能從子類而不是父類創建對象,以及如何覆蓋父類 class 的方法。

Object 面向編程(OOP)是編程中的一個大領域,但我希望我至少能幫助你入門並知道下一步該尋找什么。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM