1、类的创建
#一个模板
class Student: #Student为类的名称(类名),由一个或多个单词组成,每个单词的首字母大写,其余小写
native_pace = '福建' #直接写在类里的变量,称为类属性
#初始化方法
def __init__(self,name,age):
self.name = name #self.name是实例属性,进行了一个赋值操作,将局部变量name的值赋给了实例属性
self.age = age
# 实例方法,在类之内定义的称为方法,在类之外定义的称为函数
def eat(self):
print("学生在吃饭...")
#静态方法
@staticmethod
def method(): #静态方法中,括号里不能加self
print("我使用了staticmethod进行修饰,所以我是静态方法")
#类方法
@classmethod
def cm(cls):
print("我是类方法,因为我使用了classmethod方法进行了修饰")
#在类之内定义的称为方法,在类之外定义的称为函数
def drink():
print('喝水') #这叫做函数
类内可以定义类属性、初始化方法、实例方法、静态方法、类方法
2、实例对象的创建
#创建student类的对象
stu = Student('张三',24) #因为初始化方法中是name和age
print(id(stu))
print(type(stu))
print(stu)
输出结果:
1850941073032
<class ‘main.Student’>
<main.Student object at 0x000001AEF4AF6688>
3、实例方法的调用
(1)法一 对象名.方法名()
#法一 对象名.方法名()
stu.eat()
print(stu.name)
print(stu.age)
输出结果:
学生在吃饭…
张三
24
(2)类名.方法名(类的对象)类的对象实际就是方法定义处的self
Student.eat(stu) #与stu.eat()功能相同,都是调用Student中的eat方法
输出结果:
学生在吃饭…
4、类属性、类方法、静态方法的使用方式
4.1 类属性的使用方式
print(Student.native_pace)
stu1 = Student('张三',20)
stu2 = Student('李四',21)
print(stu1.native_pace)
print(stu2.native_pace)
Student.native_pace = '天津' #直接改
print(stu1.native_pace)
print(stu2.native_pace)
输出结果:
福建
福建
福建
天津
天津
4.2 类方法的使用方式
Student.cm() #括号里的cls在调用时不需要去传入
输出结果:
我是类方法,因为我使用了classmethod方法进行了修饰
4.3 静态方法的使用方式
Student.method()
输出结果:
我使用了staticmethod进行修饰,所以我是静态方法
5、动态绑定属性和方法
class Student:
def __init__(self,name,age):
self.name = name
self.age = age
def eat(self):
print(self.name+'在吃饭')
stu1 = Student('张三',20)
stu2 = Student('李四',30) #stu1和stu2就是实例对象
只想为stu1添加属性,不想stu2添加,就用动态绑定添加
print("——————————————为stu1动态绑定性别属性——————————————")
#只想为stu1添加属性,不想stu2添加,就用动态绑定添加
stu1.gender = '女' #直接这样添加
#在类内定义的name和age是所有student所共有的,而gender是后来只为stu1动态绑定的
print(stu1.name,stu1.age,stu1.gender)
print(stu2.name,stu2.age)
输出结果:
张三 20 女
李四 30
为stu1绑定动态方法
print("—————————————————为stu1动态绑定方法———————————————")
def show():
print("定义在类之外的,称为函数")
stu1.show = show #stu1绑定show方法
stu1.show()
#stu2.show() #会报错,因为stu2没有绑定show方法
输出结果:
定义在类之外的,称为函数