107_定义Python中的类
"""
课程视频:107_定义Python中的类
学习时间:2022/4/15 14:00
"""
# 类:是多个类似事物组成的群体,能够帮助我们快速理解和判断事物的性质
# 数据类型:不同的数据类型属于不同的类,比如str,int,float,bool
# 对象:类当中相似的不同个例,称为实例或对象,比如int当中的100,99,520
# 对象的组成:id,type,value
# Python中一切皆对象
# 创建类的语法
class Student: # Student为类的名称(类名),由一个或多个单词组成,每个单子首字母大写其余小写
native_pace = '浣熊市' # 定义在类里方法外的变量,称为类属性
def __init__(self, name, age):
self.name = name
self.age = age
# 实例方法
def eat(self):
print('学生在吃饭..')
# 静态方法
@staticmethod
def method(): # 静态方法中,()内什么都不写
print('用statistics修饰,静态方法')
# 类方法
@classmethod
def cm(cls):
print('用classmethod修饰,类方法')
# 再类之外定义的称为函数,在类之内定义的称为方法
def drink():
print('喝水')
108_对象的创建
"""
课程视频:108_对象的创建
学习时间:2022/4/15 15:04
"""
class Student: # Student为类的名称(类名),由一个或多个单词组成,每个单子首字母大写其余小写
native_pace = '浣熊市' # 定义在类里方法外的变量,称为类属性
def __init__(self, name, age):
self.name = name
self.age = age
# 实例方法
def eat(self):
print('学生在吃饭..')
# 静态方法
@staticmethod
def method(): # 静态方法中,()内什么都不写
print('用statistics修饰,静态方法')
# 类方法
@classmethod
def cm(cls):
print('用classmethod修饰,类方法')
# 再类之外定义的称为函数,在类之内定义的称为方法
def drink():
print('喝水')
# 创建Student类的对象
stu1 = Student('爱丽丝', 20)
stu1.eat() # 类名.方法名(类的对象)-->方法定义处的self
Student.eat(stu1) # 与上行功能相同,都是调用Student中的eat方法
print(stu1.name, stu1.age)
109_类属性_类方法_静态方法
"""
课程视频:109_类属性_类方法_静态方法
学习时间:2022/4/15 15:25
"""
# 类属性:类中方法外的变量,被该类的所有对象共享
# 类方法:使用@classmethod修饰的方法,使用类名直接访问
# 静态方法:使用@staticmethod修饰的方法,使用类名直接访问
class Student: # Student为类的名称(类名),由一个或多个单词组成,每个首字母大写其余小写
native_pace = '浣熊市' # 定义在类里方法外的变量,称为类属性
def __init__(self, name, age):
self.name = name
self.age = age
# 实例方法
def eat(self):
print('学生在吃饭..')
# 静态方法
@staticmethod
def method(): # 静态方法中,()内什么都不写
print('用statistics修饰,静态方法')
# 类方法
@classmethod
def cm(cls):
print('用classmethod修饰,类方法')
# 再类之外定义的称为函数,在类之内定义的称为方法
def drink():
print('喝水')
print('-----类属性的使用方式-----')
# print(Student.native_pace) # 访问类属性
stu1 = Student('爱丽丝', 20)
stu2 = Student('蕾恩', 20)
print(stu1.native_pace)
print(stu2.native_pace)
Student.native_pace = '史东微尔'
print(stu1.native_pace)
print(stu2.native_pace)
# Student是类对象
# stu1,stu2是Student类的实例对象,每个实例对象都有一个类指针指向类
print('-----类方法的使用方式-----')
Student.eat(stu1)
Student.method()
Student.cm()
110_动态绑定属性和方法
"""
课程视频:110_动态绑定属性和方法
学习时间:2022/4/15 15:56
"""
# 创建类
class Student:
def __init__(self, name, age):
# __init__是一个特殊方法用于在创建对象时进行初始化操作
# 通过这个方法我们可以为学生对象绑定name和age两个属性
self.name = name
self.age = age
def eat(self):
print(self.name + '在吃饭')
# 创建类的对象
stu1 = Student('爱丽丝', 20)
stu2 = Student('史宾斯', 30)
# Python是动态语言,在创建对象后,可以动态绑定属性和方法
stu1.gender = '女' # 创建对象后,单独为stu1绑定的属性
print(stu1.name, stu1.age, stu1.gender)
print(stu2.name, stu2.age)
#
def show(): # 定义在类之外的,称为函数
print('立即变成丧尸')
stu1.show = show # 为stu1绑定show方法,函数绑定到对象后成为方法
stu1.show()
stu2.show() # stu2没有绑定show方法,AttributeError: 'Student' object has no attribute 'show'
知识点总结