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

class Foo(object):
    """类三种方法语法形式"""
 
    def instance_method(self):
        print("是类{}的实例方法,只能被实例对象调用".format(Foo))
 
    @staticmethod
    def static_method():
        print("是静态方法")
 
    @classmethod
    def class_method(cls):
        print("是类方法")

python实例方法是需要传入参数self
加上@staticmethod,可以无视self, 普通的函数使用, 可被多个实例共享, 静态方法,参数没有要求
@classmethod,类方法,第一个参数必须要默认传类,一般习惯用cls

"""调用方法"""
# 实例方法
class Person(object):
    num = 0
    def __init__(self, name = None, age = None):
        self.name = name
        self.age = age
    def eat(self):
        print("eat food")

p = Person('老王', 24)
def run(self, speed):
    print('%s的速度是%d km/h'%(self.name, speed))

P.run = types.MethodType(run, P)
p.run(180)


# 静态方法
@staticmethod
def work():
    print('是静态方法')

p.work = work
p.work()


# 类方法
@classmethod
def go(cls):
    print('类方法')

p.go = go
p.go()

猜你喜欢

转载自blog.csdn.net/CorrectForm/article/details/83868046