zoukankan      html  css  js  c++  java
  • python 实例方法、静态方法、类方法的区别

    一、函数与方法

      在类的定义中,通过类调用和实例调用是不一样的,一个是 function 类型,另一个是 method 类型。他们的主要区别在于,函数的 传参都是显式传递的 而方法中 传参往往都会有隐式传递的,具体根据于调用方。例如示例中的 test().say通过实例调用的方式会隐式传递 self数据。

    class test:
        def say(self):
            pass
    
    print(test.say)     # <function test.say at 0x000001F5FD475730>
    print(test().say)   # <bound method test.say of <__main__.test object at 0x000001F5FD452940>>

    二、python 类的实例方法

      通常情况下,在类中定义的普通方法即为类的实例方法,实例方法第一个参数是 self(self 是一种约定习惯) 代表实例本身,当调用某个实例方法时,该实例的对象引用作为第一个参数 self 隐式的传递到方法中。

      简单来说实例方法是需要在类实例化后才能调用,如下:

    class test:
        math = 100
        # 类构造方法也是实例方法
        def __init__(self):
            self.Chinese = 90
            self.English = 80
        # 实例方法
        def say(self):
            print('我的语文成绩是:{}'.format(self.Chinese))
    
    # 实例化
    A = test()
    # 调用实例方法
    A.say()
    print(A.say)  # <bound method test.say of <__main__.test object at 0x0000020C07F28978>>

     若想直接调用方法,需要手动为 self 传入实例,如下:

    # 实例化
    A = test()
    # 为self传入实例 
    test.say(A)

    三、python 类的静态方法

      类的静态方法和我们自定义的函数基本没什么区别,没有 self,且不能访问类属性,实际项目中很少用到,因为可以使用普通函数替代。

      静态方法需要使用 @staticmethod 装饰器声明。

      有两种调用方式:类.方法名 和 实例化调用 。

    class test:
        math = 100
        # 类构造方法也是实例方法
        def __init__(self):
            self.Chinese = 90
            self.English = 80
        @staticmethod
        def say():
            print('我的语文成绩是:90')
    
    # 类.方法名
    test.say()
    print(test.say)  # <function test.say at 0x000001C2620257B8>
    # 实例化
    A=test()
    A.say()
    print(A.say)     # <function test.say at 0x000001C2620257B8>

    四、python 类的类方法

      类的类方法也必须包含一个参数,通常约定为 cls ,cls 代表 类本身(注意不是实例本身,是有区别的),python 会自动将类本身传给 cls,所有这个参数也不需要我们传值。

      类方法必须需要使用 @classmethod 装饰器申明。

      两种方式调用:类.方法名 和 实例调用。

    class test:
        math = 100
        # 类构造方法也是实例方法
        def __init__(self):
            self.Chinese = 90
            self.English = 80
        @classmethod
        def say(cls):
            print('我的数学成绩是:{}'.format(cls.math))
    
    # 类.方法名
    test.say()
    print(test.say)      # <bound method test.say of <class '__main__.test'>>
    # 实例化调用
    test().say()
    print(test().say)    # <bound method test.say of <class '__main__.test'>>

    总结一下:

    实例方法:可以获取类属性、构造函数定义的变量,属于 method 类型。只能通过实例化调用。

    静态方法:不能获取类属性、构造函数定义的变量,属于 function 类型。两种调用方式:类.方法名 ,实例化调用。

    类方法 :可以获取类属性,不能获取构造函数定义的变量,属于 method 类型。两种调用方式:类.方法名 ,实例化调用。

  • 相关阅读:
    Six steps to create google map in the HTML5
    Vocabularies on vegetable, fruit, meat etc.
    常用的Windows命令
    sqlhelper
    素材
    sql sever 跨库查询
    在annotation中却会有ERROR: Duplicate entry
    一份Java学习路线图
    Java算法实例集合(2)
    Java编程规范实践
  • 原文地址:https://www.cnblogs.com/shenh/p/13045035.html
Copyright © 2011-2022 走看看