class Student:
#Student为类的名称(类名)由一个或多个单词组成,每个单词的手写字母大写,其余小写
native_pace=‘江西’ #直接写在类里的变量,称为类属性
**#初始化方法**
def __init__(self,name,age):
self.name=name
#self.name称为实体属性,进行了一个赋值操作,将局部变量的name赋值给实体属性
self.age=age
**#实例方法——在类之外定义的称为函数,在类之内定义的称为方法**
def eat(self):
print('学生在吃饭...')
**#静态方法——使用@staticmethod进行修饰(不能使用self)**
@staticmethod
def look():
print('静态方法——使用了staticmethod的方法修饰')
**#类方法——使用@classmethod进行修饰(使用cls)**
@classmethod
def looks(cls):
print('类方法——使用classmethod进行修饰')
stu=Student(‘张三’,20)
stu.eat()#对象名.方法名
Student.eat(stu)#类名.方法名(类的对象)——实际上就是方法定义处的self
print(stu.name)
print(stu.age)
‘’‘类属性的使用方式’’’
print(Student.native_pace)
stu1=Student(‘李四’,18)
stu2=Student(‘王五’,20)
print(stu1.native_pace)#江西
print(stu2.native_pace)#江西
Student.native_pace=‘浙江’
print(stu2.native_pace)#浙江
print(stu1.native_pace)#浙江
Student.look()
Student.looks()
class scool:
def init(self,name,age):
self.name=name
self.age=age
def eat(self):
return self.name+‘在吃饭’
sc=scool(‘张三’,20)
sc1=scool(‘李四’,22)
print(sc.eat())#输出:张三在吃饭
‘’‘sc1动态绑定性别属性’’’
sc1.gender=‘男’
print(sc.name,sc.age)
print(sc1.name,sc1.age,sc1.gender,sc1.eat())
‘’‘sc动态的绑定sc2方法’’’
def sc2():
print(‘定义在类之外的,称为函数’)
sc.sc2=sc2
sc.sc2()