zoukankan      html  css  js  c++  java
  • Python 类方法、实例方法、静态方法

    实例方法:类中第一个参数为self的方法。

    类方法:类中第一个参数为类,约定写为cls,并被@classmethod修饰的方法。

    静态方法:类中被@staticmethod修饰的方法。

    类变量:定义在类的定义之后,如:METHOD 。

    实例变量:以self开头,如:self.name。

    首先查看一段代码,如下:

    class TestClassMethod(object):
    
        METHOD = 'method hoho'
    
        def __init__(self):
            self.name = 'leon'
    
        def test1(self):
            print 'test1'
            print self
    
        @classmethod
        def test2(cls):
            print cls
            print 'test2'
            print TestClassMethod.METHOD
            print '----------------'
    
        @staticmethod
        def test3():
            print TestClassMethod.METHOD
            print 'test3'
    
    if __name__ == '__main__':
        a = TestClassMethod()
        a.test1()
        a.test2()
        a.test3()
        TestClassMethod.test3()

    在TestClassMethod类中,test1位实例方法,test2为类方法,test3为静态方法。

    类和实例都可以访问静态方法,静态方法和实例方法。

    类方法和静态方法都可以访问类变量,但不能访问实例变量。

    Python既是面向对象编程的,又是面向函数编程的。

    面向对象:以类的形式实现。每个类包括属性和方法,可以通过类创建多个实例,每个实例可以有不同的属性。

    面向函数:一个单独的.py文件,里面没有类,只有一些函数和变量。

    比如:demo.py

    func demo_01():
        print "Function demo_01"

    在test.py中调用demo_01方法:

    import demo
    
    func test_01():
        print "Function test_01 begin:"
        demo.demo_01()
        print "Function test_01 end."

    导入模块后,可以直接通过"filename.methodname"的方式调用。

  • 相关阅读:
    nginx启动
    java中有三种移位运算符
    easyUI属性汇总
    rose学习
    eclipse 启动到load workbench 后静止
    nvl函数
    Io 异常: Socket closed
    编译错误和运行时错误
    java 二进制编码
    MyFormat 幫助類
  • 原文地址:https://www.cnblogs.com/xiaoerlang/p/6676792.html
Copyright © 2011-2022 走看看