简体   繁体   English

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

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

We havce 2 ways to change state of an object 我们提供了两种更改对象状态的方法

We create a method in the class and invoke it to change the state. 我们在类中创建一个方法,然后调用它来更改状态。 example

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

Or we can pass object of class to a method and change the state. 或者我们可以将类的对象传递给方法并更改状态。 example

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)

Which of the above approach is better in terms Object oriented programming? 就面向对象编程而言,以上哪种方法更好? I have done 2nd approach all the time but now I am little confused regarding which one is better. 我一直都在做第二种方法,但是现在我对哪种方法更好感到困惑。

I would suggest a third approach, instantiate the object with the new color itself, and define an external function which takes the old color and returns the 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))

Otherwise the first option is the best, since it keeps all the methods related to the Car class within the definition itself, which the second option doesn't do, where you need to explicitly pass the object to the function, (In the first option, the class instance is accessed by self ) 否则,第一个选项是最好的,因为它将与Car类相关的所有方法保留在定义本身内,而第二个选项则不这样做,在第二个选项中,您需要将对象显式传递给函数( ,则可以通过self访问类实例)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM