You need to enable JavaScript to run this app. Python子类调用父类方法为何出现None值?如何修复?
优惠活动
大模型
产品
解决方案
定价
更多

Python子类调用父类方法为何出现None值?如何修复?

问题分析与修复

为什么会出现None和换行?

你的Person.print_info()方法是直接调用print()输出内容,这个方法没有返回值(Python中没有return的函数默认返回None)。所以当你在print_employee_info()里写str(Person.print_info(self))时:

  1. 先执行Person.print_info(self),直接打印出John, age 20, height 182cm.,并且print()默认会添加换行符
  2. 然后把这个方法返回的None转成字符串,再和id_number拼接,就出现了None2230

修复代码

核心思路是让父类的方法返回信息字符串,而不是直接打印,这样子类可以拿到字符串后拼接再输出:

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

    def get_info(self):
        # 返回拼接好的字符串,而非直接打印
        return f"{self.name}, age {self.age}, height {self.height}cm."


class Employee(Person):
    def __init__(self, name, age, height, id_number):
        # Python3推荐用super()调用父类初始化,适配性更强
        super().__init__(name, age, height)
        self.id_number = id_number

    def print_employee_info(self):
        # 拼接父类信息与工号后统一打印
        full_info = self.get_info() + self.id_number
        print(full_info)

john = Employee("John", "20", "182", "2230")
john.print_employee_info()

执行后会输出你预期的结果:John, age 20, height 182cm.2230

其他需要注意的细节

  • 类型处理:目前你传入的age和height是字符串,如果后续要做数值计算(比如比较年龄、计算身高差),建议传入整数类型,f-string会自动把数字转成字符串,不用手动处理:
    john = Employee("John", 20, 182, "2230")
    
  • 父类初始化写法:super().__init__(...)比直接Person.__init__(self, ...)更灵活,后续如果修改继承关系,不需要手动修改父类名称。

内容的提问来源于stack exchange,提问作者Rok Berkopec

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 22:50:24