繁体   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