#python其实有3个方法,即静态方法(staticmethod),类方法(classmethod)和实例方法 '''实例方法调用离不开实例,需要把实例自己传给函数,类方法一样,只不过传递的是类而不是实例 静态方法以@staticmethod装饰器进行装饰,它相当于一个写在类的作用域中的普通方法; 类方法以@classmethod装饰器进行装饰,它有一个系统默认参数cls,代表的是当前类, 我们可以通过这个cls()去创建一个类的实例;''' class Person(object): def __init__(self,name,age): self.name=name self.age=age # 实例方法,只能通过实例去调用 def run(self): print(self.name+' is running......') # 类方法,访问不了实例的属性,只能访问类的属性 # 可以通过cls创建类的实例 @classmethod def cmethon(cls): print('hello') c=cls('bill',45) print(c.name) c.run() # 静态方法,访问不了实例的属性,只能访问类的属性 # 静态方法也无法创建实例 # 静态方法只是一个写在类的定义域内的普通方法而已 @staticmethod def smethon(): print('sleeping')
实例、类、静态方法
猜你喜欢
转载自blog.csdn.net/weixin_42141853/article/details/80635322
今日推荐
周排行