Python-类的方法

方法:
  可以在外部直接使用类名.方法名来调用的方法称为 类方法,类方法属于一种动态加载的概念,默认情况下只会加载某个方法,需要使用classmethod()函数来进行处理,才能直接在外部使用类名调用
 
例子:
 1 class People(object):
 2     color = 'yellow' -->类的全局静态属性
 3     def __init__(self,name,age):
 4         self.name = name -->类的动态属性
 5        self.age = age
 6  
 7     @classmethod -->装饰器版本(talk = classmothod(talk) ) --->动态类方法
 8     def talk(self): -->类的方法
 9        print('%s want to talk' % self.name )
10  
11     @staticmethod -->装饰器版本(say = classmothod(say) ) ---->静态类方法
12     def say(): -->类的方法
13        print('%s want to say' % People.color )
14  
15     #函数版本 和装饰器版本效果相同
16     talk = classmethod(talk)
17     say = staticmethod(say)
18  
19 调用方法:
20     People.talk()
21     People.say()    
 
注意:
  动态类方法:可以直接通过self.属性来访问类的全局属性,只有访问的时候配合classmethod函数,动态的去加载对应的属性。(有点省内存)
  静态类方法:不传递self参数,需要通过staticmethod函数来加载所有类属性和方法,需要通过类名.属性来调用,才可以在类外直接使用类名进行调用(优点,速度快)
  类方法的第一个参数必须是self,因为self是类本身,如果不加self,将无法通过类或实例化的类调用类方法,如果想要通过类名来调用需要配和staticmethod函数进行处理
 
原文地址:https://www.cnblogs.com/dachenzi/p/6701727.html