编程助手学Python--Deepseek对类和多继承的理解
#!/usr/bin/python3
#类定义
class people:
#定义基本属性
name = ''
age = 0
#定义私有属性,私有属性在类外部无法直接进行访问
__weight = 0
#定义构造方法
def __init__(self,n,a,w):
self.name = n
self.age = a
self.__weight = w
def speak(self):
print("%s 说: 我 %d 岁。" %(self.name,self.age))
#单继承示例
class student(people):
grade = ''
def __init__(self,n,a,w,g):
#调用父类的构函
people.__init__(self,n,a,w)
self.grade = g
#覆写父类的方法
def speak(self):
print("%s 说: 我 %d 岁了,我在读 %d 年级"%(self.name,self.age,self.grade))
#另一个类,多继承之前的准备
class speaker():
topic = ''
name = ''
def __init__(self,n,t):
self.name = n
self.topic = t
def speak(self):
print("我叫 %s,我是一个演说家,我演讲的主题是 %s"%(self.name,self.topic))
#多继承
class sample(speaker,student):
a =''
def __init__(self,n,a,w,g,t):
student.__init__(self,n,a,w,g)
speaker.__init__(self,n,t)
test = sample("Tim",25,80,4,"Python")
test.speak() 详细解释
以下是代码的详细解释,使用 Markdown 语法进行格式化:
Python 类与多继承示例
1. people
类
1.1 类定义
class people:
name = ''
age = 0
__weight = 0
people
类有三个属性:name
:公有属性,表示姓名。age
:公有属性,表示年龄。__weight
:私有属性,表示体重(以双下划线__
开头表示私有属性)。
1.2 构造函数
def __init__(self, n, a, w):
self.name = n
self.age = a
self.__weight = w
__init__
是构造函数,用于初始化对象的属性。- 参数
n
、a
、w
分别用于设置name
、age
和__weight
。
1.3 方法
def speak(self):
print("%s 说: 我 %d 岁。" % (self.name, self.age))
speak
方法用于打印对象的姓名和年龄。
2. student
类(继承自 people
)
2.1 类定义
class student(people):
grade = ''
student
类继承自people
类。- 新增一个属性
grade
,表示年级。
2.2 构造函数
def __init__(self, n, a, w, g):
people.__init__(self, n, a, w)
self.grade = g
- 调用父类
people
的构造函数初始化name
、age
和__weight
。 - 新增参数
g
用于设置grade
。
2.3 方法重写
def speak(self):
print("%s 说: 我 %d 岁了,我在读 %d 年级" % (self.name, self.age, self.grade))
- 重写
speak
方法,打印姓名、年龄和年级。
3. speaker
类
3.1 类定义
class speaker():
topic = ''
name = ''
speaker
类有两个属性:topic
:表示演讲主题。name
:表示姓名。
3.2 构造函数
def __init__(self, n, t):
self.name = n
self.topic = t
__init__
是构造函数,用于初始化对象的属性。- 参数
n
和t
分别用于设置name
和topic
。
3.3 方法
def speak(self):
print("我叫 %s,我是一个演说家,我演讲的主题是 %s" % (self.name, self.topic))
speak
方法用于打印姓名和演讲主题。
4. sample
类(多继承)
4.1 类定义
class sample(speaker, student):
a = ''
sample
类同时继承自speaker
和student
类。- 多继承的顺序决定了方法解析顺序(MRO),这里
speaker
在前,因此会优先调用speaker
的方法。
4.2 构造函数
def __init__(self, n, a, w, g, t):
student.__init__(self, n, a, w, g)
speaker.__init__(self, n, t)
- 分别调用
student
和speaker
的构造函数初始化属性。
5. 创建对象并调用方法
test = sample("Tim", 25, 80, 4, "Python")
test.speak()
-
创建一个
sample
对象test
,传入姓名"Tim"
、年龄25
、体重80
、年级4
和主题"Python"
。 -
调用
speak
方法,由于speaker
类在继承顺序中优先,因此输出:我叫 Tim,我是一个演说家,我演讲的主题是 Python
6. 总结
people
类是一个基类,包含姓名、年龄和体重属性。student
类继承自people
类,并扩展了年级属性。speaker
类是一个独立的类,包含姓名和演讲主题属性。sample
类通过多继承同时继承了speaker
和student
类。- 多继承的顺序决定了方法解析顺序(MRO),
speaker
的方法优先被调用。 - 代码展示了 Python 中类的定义、单继承、多继承和方法重写的基本用法。