了解python中的init和方法调用

时间:2018-09-06 02:34:35

标签: python-2.7

class Vehicle:
    def __init__(self, number_of_wheels, type_of_tank, seating_capacity, maximum_velocity):
        self.number_of_wheels = number_of_wheels
        self.type_of_tank = type_of_tank
        self.seating_capacity = seating_capacity
        self.maximum_velocity = maximum_velocity

    @property
    def number_of_wheels(self):
        return self.number_of_wheels

    @number_of_wheels.setter
    def number_of_wheels(number):
        self.number_of_wheels = number

    def make_noise(self):
        print('VRUUUUUUUM')

tesla_model_s = Vehicle(4, 'electric', 5, 250)
print('number of wheels',tesla_model_s.number_of_wheels) # 4
tesla_model_s.number_of_wheels = 2 # setting number of wheels to 2
print('updated number of wheels',tesla_model_s.number_of_wheels) # 2
tesla_model_s.make_noise() # VRUUUUUUUM

运行此代码时出现以下错误,我认为可能是由于getter和setter所致。谁能帮我解决这个问题。

    Traceback (most recent call last):
      File "classes.py", line 23, in <module>
        tesla_model_s.make_noise() # VRUUUUUUUM
    AttributeError: Vehicle instance has no attribute 'make_noise'

0 个答案:

没有答案