类方法

'''
类方法(classmethod装饰器)
给类方法加入classmethod装饰器后,类本身可以直接调用该方法无需再进行实例化过程(当然,实例也可调用该方法)
'''

class School:
   '''这是一个学校的类'''
   country = 'china'
   def __init__(self, name, type):
      self.name = name
      self.type = type

   def tell_info(self):
      print('%s学校是%s的' % (self.name, self.type))

print(School.country)
s1 = School('希望小学', '公立')
School.tell_info(s1) # 当用类直接调用类方法时,由于类方法有实例本身这个参数,所以还需要进行一步实例化的操作,然后再进行调用


class School1:
   '''这是另外一个学校的类'''
   country = 'china'
   def __init__(self, name, type):
      self.name = name
      self.type = type

   @classmethod
   def tell_info(cls, name1, type1): # 此时这里无法调用实例的数据属性
      print(cls) # <class '__main__.School1'>
      print('%s学校是%s的' % (name1, type1), cls.country) # 可调用类本身的数据属性

School1.tell_info('梦想', '私立') # 此时无需实例化,也可直接用类调用方法;类自动把类名传给了cls这个参数;当类进行实例化后,实例也可以调用这个方法
while True: print('studying...')
原文地址:https://www.cnblogs.com/xuewei95/p/14651057.html