简体   繁体   English

难以理解Python OOP

[英]Having difficulty understanding Python OOP

I'm fairly green to OOP and I was just playing around with it in Python and came across something I can't explain so hopefully you guys will be able to help. 我对OOP相当绿色,我只是在Python中玩它并遇到了一些我无法解释的事情,所以希望你们能够提供帮助。

I was playing with the code below: 我正在玩下面的代码:

class Car():
    def __init__(self, brand, model, speed):
        self.brand = brand
        self.model = model
        self.speed = speed

    def increase_speed(self):
        return self.speed + 1


    def decrease_speed(self, decrease_by):
        return self.speed - decrease_by

car1 = Car("tesla","x",30)
print(car1.brand)
print(car1.speed)
print(car1.increase_speed())
print(car1.speed)
print(car1.decrease_speed(10))

My question is, I am expecting after increasing the speed, car1's speed will be 31 but instead it prints out 30. Why is it that way and how should the code be written for the speed to be 31 instead? 我的问题是,我期待在提高速度之后,car1的速度将是31但是它打印出来30.为什么会这样,为什么这样的代码应该写为速度为31?

def increase_speed(self):
    self.speed += 1
    return self.speed

Previously you did not increase your speed, rather you just return a value that is equal to the speed plus 1. Similarly, change your decrease_speed function. 以前你没有提高速度,而只是返回一个等于速度加1的值。同样,改变你的decrease_speed函数。

方法increase_speed只是返回self.speed + 1,如果你想将self.speed = self.speed + 1所需的速度更新为方法增加速度。

Instead of returning the values, set them on the attributes: 而不是返回值,而是在属性上设置它们:

class Car():
    def __init__(self, brand, model, speed):
        self.brand = brand
        self.model = model
        self.speed = speed

    def increase_speed(self):
        self.speed = self.speed + 1


    def decrease_speed(self, decrease_by):
        self.speed = self.speed - decrease_by

I deliberately don't return the changed speed anymore, as it's good style (at least with methods mainly setting attributes) to either return something or change state: 我故意不再返回改变的速度,因为它的好样式(至少用主要设置属性的方法) 要么返回一些东西要么改变状态:

car1 = Car("tesla","x",30)
print(car1.brand)
print(car1.speed)
car1.increase_speed()
print(car1.speed)
car1.decrease_speed(10)
print(car1.speed)

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

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