You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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)

关键修改说明

  1. 方法类型调整:将filtering改为@staticmethod,无需创建Vehicles实例就能直接通过类调用
  2. 变量作用域处理:调用filtering时把返回值赋值给全局变量filtered_cars,供后续循环使用
  3. 修复__str__方法:让__str__返回字符串,直接打印实例时会自动调用该方法,输出正确描述,避免出现None
  4. 简化lambda表达式:原lambda的True if...else False可直接简化为判断条件本身,代码更简洁

内容的提问来源于stack exchange,提问作者Raphael Silva

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 21:30:47