Python类方法返回列表外部调用问题:无法访问new_list
Python类方法调用与作用域问题修复
原代码存在的问题
filtering是Vehicles类的实例方法,直接全局调用会报错,必须通过类实例调用,或者改为静态/类方法- 方法内部的
new_list属于局部变量,外部无法直接访问,需要接收方法的返回值来获取筛选结果 __str__方法错误:该方法应该返回字符串而非直接打印,否则打印实例时会输出None
修正后的代码
class Vehicles: color = '' wheels = 0 def __init__(self, color, wheels): self.color = color self.wheels = wheels # 改为静态方法,无需实例即可调用 @staticmethod def filtering(list_vehicles, vehicle): # 简化lambda表达式 return list(filter(lambda x: x.__class__.__name__ == vehicle, list_vehicles)) def __str__(self): # 返回字符串而不是直接打印 return f"This bus is {self.color} and has {self.wheels} wheels." bus1 = Vehicles("white", 6) print(bus1) # 直接打印实例,自动调用__str__ class Car(Vehicles): speed = 0 changes = 0 def __init__(self, color, wheels, speed, changes): super().__init__(color, wheels) self.speed = speed self.changes = changes def __str__(self): return f"This car is {self.color}, has {self.wheels} wheels, its speed is {self.speed} mph and it has {self.changes} gears." car1 = Car("red", 4, 110, 5) print(car1) car2 = Car("blue", 4, 130, 6) print(car2) # 调用静态方法并接收返回结果 filtered_cars = Vehicles.filtering([bus1, car1, car2], "Car") # 输出筛选后的实例 print("\n筛选出的Car实例:") for x in filtered_cars: print(x)
关键修改说明
- 方法类型调整:将
filtering改为@staticmethod,无需创建Vehicles实例就能直接通过类调用 - 变量作用域处理:调用
filtering时把返回值赋值给全局变量filtered_cars,供后续循环使用 - 修复__str__方法:让
__str__返回字符串,直接打印实例时会自动调用该方法,输出正确描述,避免出现None - 简化lambda表达式:原lambda的
True if...else False可直接简化为判断条件本身,代码更简洁
内容的提问来源于stack exchange,提问作者Raphael Silva
相关产品推荐
相关产品推荐

