簡體   English   中英

在OOP中定義Class方法與將對象作為參數傳遞給Function

[英]Defining a Class method vs Passing object as parameter to an Function in OOP

我們提供了兩種更改對象狀態的方法

我們在類中創建一個方法,然后調用它來更改狀態。

class Car:
    def __init__(self, color):
        self.car_color = color

    # this method may have complex logic of computing the next color. for simplicity, I created this method just like a setter.
    def change_color(self, new_color):
        self.car_color = new_color

或者我們可以將類的對象傳遞給方法並更改狀態。

class Car:
    def __init__(self, color):
        self.car_color = color
    # these are just getters and setter and wont have complicated logic while setting color.
    def set_color(self, new_color):
        self.car_color = new_color
    def get_color(self):
        return self.car_color

# this method will have all the complicated logic to be performed while changing color of car.
def change_color(car_object, new_color):
    car_object.set_color(new_color)

就面向對象編程而言,以上哪種方法更好? 我一直都在做第二種方法,但是現在我對哪種方法更好感到困惑。

我建議使用第三種方法,用新顏色本身實例化對象,並定義一個接受舊顏色並返回新顏色的外部函數。

class Car:
    def __init__(self, color):
        self.car_color = color

#A function which takes in the old_color and provides the new color
def logic_to_change_color(old_color):
    #do stuff
    return new_color

car = Car(logic_to_change_color(old_color))

否則,第一個選項是最好的,因為它將與Car類相關的所有方法保留在定義本身內,而第二個選項則不這樣做,在第二個選項中,您需要將對象顯式傳遞給函數( ,則可以通過self訪問類實例)

暫無
暫無

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

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