类和对象的创建及使用:
‘
’
创建类
class Student:
name='陌言'
age=20
place='Putian'
#构造方法
def __init__(self):
pass
#构造方法如果写了两个会以第二个为准,相当于第一个没写(似乎);
# def __init__(self,name,age,place):
# self.name=name
# self.age=age
# self.place=place
#实例方法
def name_change(self,name): #方法名字尽量不要和类里面变量名字相同,不然调用变量的时候回变成调用类方法,输出了地址类型之类的(似乎)
self.name=name
def age_change(self,age):
self.age=age
def place_change(self,place):
self.place=place
def inf(self):
print(f'Name:{self.name}; Age:{self.age}; Place:{self.place}')
#静态方法
@staticmethod
def method():
print('静态方法!')
#类方法
@classmethod
def cm(cls):
print('类方法')
注意点:
#构造方法如果写了两个会以第二个为准,相当于第一个没写(似乎);
#方法名字尽量不要和类里面变量名字相同,不然调用变量的时候回变成调用类方法,输出了地址类型之类的(似乎)
‘
’
两种调用方法的方式:
1 对象名.方法名
2 类名.方法名(对象)
stu=Student()
print('Student1:',end='\t')
stu.inf()
stu2=Student()
stu2.age_change(18) #修改数据
stu2.place_change('Dream')
print('Student2:',end='\t')
stu2.inf()
#第二种输出方式
Student.inf(stu)
Student.inf(stu2)
#可以通过 对象.变量名 直接调用类里面的属性
print('直接调用Place:',stu.place)
print('类默认Place:',Student.place)
Student.place='somewhere' #仅修改了默认值,对于已修改的非默认值不进行改变
stu.inf()
stu2.inf()
stu3=Student()
stu3.name_change('someone')
stu3.inf()
结果:
Student1: Name:陌言; Age:20; Place:Putian
Student2: Name:陌言; Age:18; Place:Dream
Name:陌言; Age:20; Place:Putian
Name:陌言; Age:18; Place:Dream
直接调用Place: Putian
类默认Place: Putian
Name:陌言; Age:20; Place:somewhere
Name:陌言; Age:18; Place:Dream
Name:someone; Age:20; Place:somewhere
‘’
类方法和静态方法的使用
#类方法的使用,使用类名直接访问
Student.cm()
#静态方法,使用类名直接访问
Student.method()
类方法
静态方法!
‘
‘
’
动态绑定
#动态绑定属性
stu.game='Genshin'
print(stu.name,stu.age,stu.game) #game属性仅存在于stu中
#print(stu2.name,stu2.age,stu2.game) 报错#AttributeError: 'Student' object has no attribute 'game'
#动态绑定方法
def show():
print('这是函数!不是实例方法。')
stu.show=show()
stu.show
#stu2.show #报错,AttributeError: 'Student' object has no attribute 'show'
结果:
陌言 20 Genshin
这是函数!不是实例方法。