• python静态方法和类方法


    静态方法是类和类的独立实例。它是在类范围中定义的方法。

    它可以直接由类和实例被称为。

    类方法和静态方法都要使用装饰器来定义,定义的基本格式是:

    @staticmethod

    def <function name>():

             #do something

    类方法定义的基本格式是:

    @ classmethod

    def <function name>(cls):

             #do something

    类方法与成员方法不同的是,它须要传入參数cls,cls代表类。

    class Myclass():
    	x='class';
    	def __init__(self):
    		self.x='instance';
    	@ staticmethod
    	def staticmd():
    		print 'static method';
    	@classmethod
    	def classmd(cls):
    		print cls.x;
    		
    	def inst(self):
    		print self.x;

    类的实例能够訪问静态方法。类方法,和成员方法

    >>>test=Myclass()

    >>>test.staticmd()

    static method

    >>>test.classmd()

    class

    >>>test.inst()

    instance

    类能够訪问静态方法和类方法,但不能訪问成员方法

    >>>Myclass.staticmd()

    static method

    >>>Myclass.classmd()

    class 

    >>>Myclass.inst()

    TypeError: unbound method inst() must be called with Myclass instance as first argument(got nothing instead)

    静态方法能够被继承,以下的derived1类继承Myclass类,derived1类也有了静态方法。derived1的实例能够直接调用staticmd()方法

    class derived1(Myclass):

             def__init__(self):

                       Myclass.__init__(self);

    >>>d=derived1()

    >>>d.staticmd()

    static method

    类方法也能够被继承,派生类的类的实例訪问类方法。将会自己主动调用派生类版本号的类方法,实现多态。

    以下的derived2类继承自Myclass,derived2类能够调用类方法classmd(cls),此时cls指的是derived2.

    class derived2(Myclass):

             x="derived2";

             def__init__(self):

                       Myclass.__init__(self);

    >>>d2=derived2()

    >>>d2.classmd()

    derived2


    版权声明:本文博主原创文章。博客,未经同意不得转载。

  • 相关阅读:
    Maven 集成Tomcat插件
    dubbo 序列化 问题 属性值 丢失 ArrayList 解决
    docker 中安装 FastDFS 总结
    docker 从容器中拷文件到宿主机器中
    db2 相关命令
    Webphere WAS 启动
    CKEDITOR 4.6.X 版本 插件 弹出对话框 Dialog中 表格 Table 自定义样式Style 问题
    SpringMVC JSONP JSON支持
    CKEDITOR 3.4.2中 按钮事件中 动态改变图标和title 获取按钮
    git回退到远程某个版本
  • 原文地址:https://www.cnblogs.com/gcczhongduan/p/4815425.html
Copyright © 2020-2023  润新知