首页 > 解决方案 > 为什么 print 函数在方法中不起作用:get_details() 并且没有为 print(x.increment_odometer) 返回?

问题描述

class Car:
    def __init__(self,make,model,year): 
        self.make=make
        self.model=model
        self.year=year
        self.odometer_reading=0 
        
    def get_details(self): #SELF allows access of attributes and methods of a class 
        details=print((f'The make is: {self.make}, the model is: {self.model}, & the year is: {self.year}\n'))
        #return details without print function works? i.w. details=rest of the line without print + return details (next line)
    
    def read_odometer(self): #reading the value (default)
        print(f'\nReading: {self.odometer_reading}')

        
    def update_odometer(self,mileage): 

        if mileage>=self.odometer_reading:
            print('\nReading has been changed')
            self.odometer_reading=mileage
        else:
            print('\nCan, not change ')
    def increment_odometer(self,miles):
        self.odometer_reading+=miles

x.get_details() #trying to modify print(x.get_details()) which does work. Why does print need to be supplied here? 

#incrementing the odometer 

print(x.increment_odometer(50)) #why is this none?

我正在学习课程并且对某些方面感到困惑:

  1. 为什么方法 get_details() 需要“返回详细信息”行?通常,具有 def f(): print('a') 的简单函数调用可以工作,因此会造成混淆。
  2. print(x.increment_odometer(50)) 是无。在 increment_odometer() 方法中可能需要一个函数返回?

混淆点已在代码中注释。请启发我。

真挚地。

标签: python-3.xclassmethodsattributesreturn

解决方案


推荐阅读