定义 Class 方法与将对象作为参数传递给 OOP 中的函数

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

我们有两种改变对象状态的方法

我们在 class 中创建一个方法并调用它来改变状态。示例

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 的对象传递给一个方法并改变状态。示例

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)

以上哪种方法在面向对象编程方面更好? 我一直采用第二种方法,但现在我对哪种方法更好感到困惑。

我会建议第三种方法,用新颜色本身实例化对象,并定义一个采用旧颜色和 returns 新颜色的外部函数

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 class 相关的方法保留在定义本身中,而第二个选项没有,您需要在其中显式地将对象传递给函数,(在第一个选项中,class 实例由 self 访问)