python 实例方法、类方法和静态方法

#!/usr/bin/env python3.6
#-*- coding:utf-8 -*-
#
class Person(object):
    city = 'Beijing'

    def __init__(self,name):
        self.name = name
        self.age =28

    # 实例方法
    def showInfo(self):
        info = "name: %s, age: %s" % (self.name, self.age)
        print(info)

    # 类方法
    @classmethod
    def sayHi(cls):
        print('hi, i am in %s' % cls.city)

    # 静态方法
    @staticmethod
    def sayBye():
        print('byebye')

1、实例方法

  实例方法就是普通的对象方法,只能通过对象实例来调用,调用时参数self会自动关联到对象实例。

2、类方法

  需要指定修饰器@classmethod,类方法可以通过类直接调用,也可以通过对象直接调用,但参数cls将自动关联到类。

3、静态方法

  需要指定修饰器@staticmethod,没有参数self,可以直接通过类来调用;是个独立的函数,仅仅是存在于类的名称空间中,便于使用和维护。

原文地址:https://www.cnblogs.com/houyongchong/p/method.html