Python面向对象
类的定义
class Athlete:
# 类属性
Athlete_about = "这是一个运动员类"
# 构造方法
def __init__(self, name, times):
self.name = name
self.times = times
self.Athlete_about = "这不是"
# 方法
def show(self):
print(f"{self.name}:{self.times}")
# 类方法
@classmethod
def showMe(self):
print(self.Athlete_about)
amy = Athlete("amy", ['2.23', '3.44'])
amy.show()
self代表类的实例,而非类
Python内置类属性
- dict : 类的属性(包含一个字典,由类的数据属性组成)
- doc :类的文档字符串
- name: 类名
- module: 类定义所在的模块(类的全名是’main.className’,如果类位于一个导入模块mymod中,那么className.module 等于 mymod)
- bases : 类的所有父类构成元素(包含了一个由所有父类组成的元组)
- 可以使用点号 . 来访问对象的属性
创建对象
#定义橄榄球运送员类
class Rugby(Athlete):
def __init__(self,a_name,a_bod,a_squat,a_times):
#调用父类__init__
Athlete.__init__(self,a_name,a_bod,a_times)
#深蹲次数
self.squat = a_squat
# 继承后下面两个函数就在Rugby类中,只是看不到而已
# def top3(self):
# return sorted(set([self.sanitize(t) for t in self.times]))[0:3]
# def sanitize(self,time_string):
# if '-' in time_string:
# splitter = '-'
# elif ':' in time_string:
# splitter = ':'
# else:
# return (time_string)
# (mins,secs) = time_string.split(splitter)
# return (mins+'.'+secs)
如果某个对象改变类属性会怎么样?
继承
定义:
class 子类名(父类名):
情况1,如果子类有新增的属性,那么需要在子类__init__方法中,调用父类的__init__方法
情况2,如果子类没有新增的属性,子类不需要写__init__方法
#定义橄榄球运送员类
class Rugby(Athlete):
def __init__(self,a_name,a_bod,a_squat,a_times):
#调用父类__init__
Athlete.__init__(self,a_name,a_bod,a_times)
#深蹲次数
self.squat = a_squat
# 继承后下面两个函数就在Rugby类中,只是看不到而已
# def top3(self):
# return sorted(set([self.sanitize(t) for t in self.times]))[0:3]
# def sanitize(self,time_string):
# if '-' in time_string:
# splitter = '-'
# elif ':' in time_string:
# splitter = ':'
# else:
# return (time_string)
# (mins,secs) = time_string.split(splitter)
# return (mins+'.'+secs)
法重写
子类方法与父类方法完全相同,子类若重写了父类的方法,则子类对象调用方法时就是调用的自己类中重新的方法。
多继承
class Father():
def talk(self):
print("---爸爸的表达能力---")
class Mather():
def smart(self):
print("---妈妈聪明的头脑---")
class Child(Father,Mather):
pass
child1 = Child()
child1.talk()
child1.smart()