Python 类方法、实例方法、静态方法

总结

  • classmethod(类方法) 第一个参数永远是 cls, instancemethod(实例方法) 第一个参数永远是 self。
  • cls包含了全部的类属性,self包含了实例属性。
  • 在定义的时候形参需要填写(self,cls),在调用的时候不需要填写实参。
  • Python中静态方法类似类外的普通函数,只不过将他放在类内了而已,不可以直接使用self和cls中的内容,cls中内容可以用类名.属性的形式访问与修改。
  • 类方法与类属性,和实例方法与实例属性的关系,更像是其他语言静态与实例的关系,实例可以访问类,类不可以访问实例且全部实例对象共用一份类属性类方法。
class Person:
    # 类属性
    a = 1

    # 类方法
    @classmethod
    def cm(cls):
        print(cls.a)

    # 静态方法
    @staticmethod
    def sm():
        print("sm()")

    def __init__(self, name, age):
        # 实例属性
        self.name = name
        self.age = age

    # 实例属性方法
    def out(self):
        print('name:', self.name + ';', 'age:', self.age)

# 实例
Instance = Person('adam', 12)
Instance.out()
Instance.sm()
"""
output:
     name: adam; age: 12
     sm()
"""

# 静态方法
Person.sm()

"""
output:
     sm()
"""

# 类方法
Person.cm()
print(Person.a)

"""
output:
     1
     1
"""
  • 上述代码在实例中调用了实例方法out(),使用类名.属性调用了静态方法sm()和类成员a、cm(),可以看出实例对象可以调用静态方法和类方法
@staticmethod
def fun():
    print("fun")

@classmethod
def funclass(cls):
    print("funclass")

Person.sm = fun
Instance.sm()

Person.cm = funclass
Instance.cm()

Person.a = 9
print(Instance.a)

"""
output:
     fun
     funclass
     9
"""
  • 上述代码修改了静态方法sm()和类属性类方法a、cm(),使用实例对象调用,表明类方法、静态方法全部对象共用一份
import types
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age


def out(self):
    print(self.name, self.age)


p = Person('adamr', 12)
print(p.name)
p.out = types.MethodType(out, p)
p.out()
"""
output:
     adamr
     adamr 12
"""
p1 = Person('rick', 21)
print(p1.name)
p1.out()
"""
output:
     rick
     AttributeError: 'Person' object has no attribute 'out'
"""
  • 上述代码证明实例方法、属性,每个对象都独享一份
  • types.MethodType(method, instance)是给实例添加方法的函数,需要import types
posted @ 2020-11-13 16:52  探索星空  阅读(94)  评论(0编辑  收藏  举报