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

Python中如何调用类方法?调用Cat类cat_age方法报NameError求助

问题原因分析
  • cat_age是Cat类的实例方法,必须通过Cat类的实例(比如cat1、cat2)调用,不能直接当作全局函数使用。你直接写cat_age(...)时,Python会认为这是一个未定义的全局函数,因此抛出NameError。
  • 另外这个方法的设计逻辑也不合理:作为实例方法却没有用到实例自身的age属性,反而靠外部传参计算最大值,完全浪费了类的特性。
修正方案

提供三种常用的修正思路:

思路1:转为普通全局函数

既然方法不需要依赖Cat实例的属性,直接把它从类中提取为全局函数:

def cat_age(*args):
    return max(args)

class Cat:
    def __init__(self, name, age):
        self.name = name
        self.age = age

cat1 = Cat('Pinky', 10)
cat2 = Cat('Tinky', 11)
cat3 = Cat('Sinky', 13)

print(f'The oldest cat is {cat_age(cat1.age, cat2.age, cat3.age)} years old')

思路2:改为静态方法保留在类中

如果想让方法属于Cat类,用@staticmethod装饰器把它转为静态方法,通过类名调用:

class Cat:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    @staticmethod
    def cat_age(*args):
        return max(args)

cat1 = Cat('Pinky', 10)
cat2 = Cat('Tinky', 11)
cat3 = Cat('Sinky', 13)

print(f'The oldest cat is {Cat.cat_age(cat1.age, cat2.age, cat3.age)} years old')

思路3:贴合类设计的优化写法(推荐)

直接实现一个类方法,接收Cat实例并返回年龄最大的猫的信息,更符合面向对象的设计逻辑:

class Cat:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    @classmethod
    def find_oldest(cls, *cats):
        oldest_cat = max(cats, key=lambda cat: cat.age)
        return oldest_cat.name, oldest_cat.age

cat1 = Cat('Pinky', 10)
cat2 = Cat('Tinky', 11)
cat3 = Cat('Sinky', 13)

name, age = Cat.find_oldest(cat1, cat2, cat3)
print(f'The oldest cat is {name}, {age} years old')

内容的提问来源于stack exchange,提问作者Bilal Anees

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 23:27:14