@property
将方法转变为属性
添加前
class A():
def write(self):
print('厉害')
a = A()
a.write()#方法
添加后
class A():
@property
def write(self):
print('厉害')
a = A()
a.write#属性
@staticmethod
可直接被类调用,也可以通过类实例化后调用
类实例化后调用
class A():
@staticmethod
def write(): #无self
print('厉害')
a = A()#实例化
a.write()
直接调动
class A():
@staticmethod
def write():
print('厉害')
A.write()
@classmethod
**补充类变量和实例变量
**类变量为具体有的变量,实例变量为实例化之后才有的
类变量与实例变量的区别
class Student():
age = 10
name = 'liu' #类变量
def __init__(self, age, name):
self.age = age
self.name = name #实例变量
print(Student.age, Student.name) #类直接调用了
#10, ‘liu’
student1 = Student(20, 'cai')
print(student1.age, student1.name)#实例化后调用了
#20, ‘cai’
classmethod类方法的特点是只能访问类变量,不能访问实例变量,且无类变量时会报错,可类直接调用,也可实例化类后调用
class Student():
name = 'liu' #类变量
def __init__(self, name):
self.name = name #后续实例变量位置
@classmethod #类方法
def eat(self, food):
print(self.name, '吃', food)
实例化
student1 = Student('cai') #实例化后,实例变量name=‘cai’
student1.eat('zhurou')
#结果:liu 吃 zhurou
直接类调用
Student('cai').eat('zhurou')
#结果:liu 吃 zhurou