我们提供了两种更改对象状态的方法
我们在类中创建一个方法,并调用它来更改状态。例子
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)
在面向对象编程方面,上述方法中哪个更好? 我一直都在做第二种方法,但是现在我对哪种方法更好感到困惑。
答案 0 :(得分:1)
我建议采用第三种方法,用新颜色本身实例化对象,并定义一个采用旧颜色并返回新颜色的外部函数
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
访问)