- 类属性——直属于类下面的,代表无论有多少对象,对象的属性都一样
class Student:
school='清华大学'
- 实例属性——只有建立了对象,实例属性才会存在,在建立对象是也会传入实参,即传入self后的形参对应的实参。
class Student:
def __init__(self,name,score):
self.name=name #self.name为实例属性name为形参
self.score=score
s1=Student('张三',100)
print(s1.name)
print(s1.score)
- 类方法——是为类属性所服务的,使用@classmethod作为方法的首行,cls代表类对象本身。没有对象出现,所以不可调用实例属性
class Student:
school='清华大学'
def __init__(self,name):
self.name=name
@classmethod
def printSchool(cls):
print(cls.school)
#print(cls.name) 不可调用实例属性
Student.printSchool()
- 静态方法——与类对象无关,只是单纯得放在类下面,使用@staticmethod作为方法的首行,调用时通过类调用而已。也没有对象出现,所以也不可调用实例属性
class Student:
@staticmethod
def add(a,b):
print('{}+{}={}'.format(a,b,(a+b)))
Student.add(10,20)