简体   繁体   中英

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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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