概述
Python从设计之初就是面向对象的编程语言,所以在Python中创建一个类和对象是轻而易举的。
本文就Python的面向对象编程进行分享。
在python中类定义的基本格式如下
class 类名:
def __init__(self):
# 初始化
def func_1(self, param):
# 方法1
def func_n(self, param):
# 方法n
# 可以有N个方法
下面我们用上述基本格式来定义一个简单的类,并创建该类的对象。
# 定义一个基本类
class DemoClass:
def __init__(self):
print("初始化")
def output(self, text):
# 输出text到console
print(text)
def output_none(self):
# 不带参数的方法
print("我不能传入参数")
if __name__ == "__main__":
# 创建一个类对象
demo_obj = DemoClass()
# 调用output
demo_obj.output("我是参数")
# 调用output_none
demo_obj.output_none()
下面我们通过对上述基础实例进行扩展,来体验下继承的特性。
# -*- coding:utf-8 -*-
__author__ = '苦叶子'
# 定义一个基本类
class DemoClass:
def __init__(self):
print("初始化")
def output(self, text):
# 输出text到console
print(text)
def output_none(self):
# 不带参数的方法
print("我不能传入参数")
# 继承DemoClass
class ChildDemoClass(DemoClass):
def __init__(self):
print("我是子类")
# 重写output_none
def output_none(self):
print("我是子类不能传参的方法")
if __name__ == "__main__":
# 创建一个类对象
demo_obj = DemoClass()
# 调用output
demo_obj.output("我是参数")
# 调用output_none
demo_obj.output_none()
print("-----------------------------------")
# 创建子类的对象
child_demo_obj = ChildDemoClass()
# 调用output, 调用的是父类的方法
child_demo_obj.output("我是参数")
# 调用output_none, 调用的是自己的方法,即重写后的方法
child_demo_obj.output_none()
通过上述的两个实例,大家应该对类和对象有个初步的掌握了,下面我们对类做一个基本的小结:
对于类的其他特性大家可以参阅更详细的文档或书籍。