python 类函数,实例函数,静态函数

参考自

class Function(object):
    # 在类定义中定义变量
    cls_variable = "class varibale"

    def __init__(self):
        # 在构造函数中创建变量
        self.__instance_variable = "instance variable"

    def instance_method(self):
        print(self.cls_variable)
        print(self.__instance_variable)
        print("this is a instance method")

    @staticmethod
    def static_method():
        print(Function.cls_variable)
        # print(Function.__instance_variable) 此处会报错,无法访问实例变量
        print("this is a static method")

    @classmethod
    def class_method(cls):
        print(cls.cls_variable)
        # print(cls.__instance_variable) 此处会报错,无法访问实例变量
        print("this is a class method")

    @classmethod
    def set_class_variable(cls):
        cls.cls_variable = 'new class variable'

    def set_instace_varibale(self):
        self.__instance_variable = 'new instance varibale'

# 类实例可以调用类方法和静态方法
function1 = Function()
function1.set_class_variable()
function1.class_method()
function1.instance_method()
function1.static_method()

function2 = Function()
function2.set_instace_varibale()
function2.class_method()
function2.instance_method()
function2.static_method()

类函数和静态函数的主要区别:
1. 访问类属性以及调用类函数

1. cls.属性 & cls.类函数
2. 类名.属性 & 类名.类函数 

2. 继承的不同

class Function(object):
    X = 1
    Y = 2

    @staticmethod
    def averag(*mixes):
        return sum(mixes) / len(mixes)

    @staticmethod
    def static_method():
        # 通过function调用,如果类名修改,此处需要修改不太方便
        return Function.averag(Function.X, Function.Y)


    @classmethod
    def class_method(cls):
        return cls.averag(cls.X, cls.Y)

class Subclass(Function):
    X =3
    Y = 5
    @staticmethod
    def averag(*mixes):
        return sum(mixes) / 3

func = Subclass()
print(func.static_method()) # Function.averag(Function.X, Function.Y) = 1.5
print(func.class_method()) # Subclass.averag(Subclass.X, Subclass.Y) = 2.66666666666

更多

    原文作者:jason_cuijiahui
    原文地址: https://blog.csdn.net/jason_cuijiahui/article/details/80331291
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞