Python中创建子类的方法与经典类声明

陆遥
陆遥
发布时间:2026-10-13| 3人浏览过
原创

本文介绍了Python中创建子类的基本方法。通过具体代码示例,展示了如何定义父类与子类,以及经典类(无父类)的声明方式。内容涵盖类实例化、方法调用及继承关系的实现细节,旨在帮助读者理解Python面向对象编程中的继承机制。

Python创建子类概述

本文通过具体实例详细解析了Python中创建子类的方法,供读者参考学习。

经典类与父类声明

若定义的类未从任何祖先类派生,可显式使用object作为父类名称。经典类的声明与普通类略有不同,其特点在于不显式指定父类,即不使用圆括号进行继承声明。


# !/usr/bin/env python
# -*- coding: utf-8 -*-
class ClassicClassWithoutSuperclasses:
  def fun1(self):
    print 'aaaaaaa'
a=ClassicClassWithoutSuperclasses()
print a
print type(a)
print a.fun1()


运行环境为C:\Python27\python.exe,执行脚本路径为C:/Users/TLCB/PycharmProjects/untitled/eeeee/a5.py。输出结果显示实例对象位于内存地址0x0047BDF0,类型为<type 'instance'>,并打印出字符串'aaaaaaa',最终返回None。

子类继承示例

前文已展示部分类和子类的示例,此处补充一个更简单的继承示例以作说明。


class Parent(object): # define parent class 定义父类
 def parentMethod(self):
  print 'calling parent method



# !/usr/bin/env python
# -*- coding: utf-8 -*-
class Parent(object): # define parent class 定义父类
 def parentMethod(self):
  print 'calling parent method'
class Child(Parent): # define child class 定义子类
 def childMethod(self):
  print 'calling child method'
a=Parent() # instance of parent 父类的实例
print a.parentMethod()

运行环境为C:\Python27\python.exe,执行脚本路径为C:/Users/TLCB/PycharmProjects/untitled/eeeee/a5.py。程序输出'calling parent method',随后返回None,表明父类方法被成功调用。


>>> c = Child() # instance of child 子类的实例
>>> c.childMethod() # child calls its method 子类调用它的方法
calling child method
>>> c.parentMethod() # calls parent's method 调用父类的方法
calling parent method

相关学习资源

如需进一步了解Python相关知识,建议查阅本站专题:《Python面向对象程序设计入门与进阶教程》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python编码操作技巧总结》及《Python入门与进阶经典教程》。

希望上述内容对您的Python程序设计有所帮助。

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。