python方法


title: 方法
date: 2018-4-5
categories:

  • python
    tags:
  • python

函数与方法

  • 方法是类内部定义函数,只不过这个函数的第一个是 self (可以认为方法是类属性,但不是实例属性)。
  • 必须将类实例化后,才能通过实例调用该类的方法。调用的时候在方法后面要有括号(括号后面默认有 self 参数,但是不写出来)。

绑定方法

通过实例调用方法,称之为方法绑定在实例上。
就是常规的形式。比如:

class Person(object):
    def foo(self):
        pass

如果要调用 Person.foo()方法,必须:

pp = Person() #实例化
pp.foo()

非绑定方法

使用 super 函数
(略)

静态方法和类方法

一般类的方法的第一个参数必须是 self,并且如果要调用类的方法,要通过类的实例,即方法绑定实例后才能由实例调用。如果不能绑定,一般在继承关系的类之间,可以用 super 函数等方法调用。

# -*- coding: utf-8 -*-

__metaclass__ = type

class StaticMethod:
    @staticmethod #表示下面的方法是静态方法
    def foo(): #不需要self
        print('This is static method foo()')

class ClassMethod:
    @classmethod #表示下面的方法是类方法
    def doo(cls): #必须要有cls这个参数
        print('This is class method doo()')
        print('doo() is part of class:', cls.__name__)

if __name__ == '__main__':
    static_foo = StaticMethod()
    static_foo.foo() #访问实例的方法
    StaticMethod.foo() #通过类访问类的方法
    print('*******************')
    class_doo = ClassMethod()
    class_doo.doo() #访问实例的方法
    ClassMethod.doo() #通过类访问类的方法

输出结果:

This is static method foo()
This is static method foo()
*******************
This is class method doo()
doo() is part of class: ClassMethod
This is class method doo()
doo() is part of class: ClassMethod

静态方法

@staticmethod声明
静态方法也是方法,所以依然用 def 语句类定义。需要注意的是该方法后面的括号内没有 self,也正是这样才叫它静态方法。
静态方法无法访问实例变量、类和实例的属性,因为它们都是借助 self 来传递数据的。

类方法

@classmethod声明
类方法,区别也是在参数上。类方法的参数也没有 self,但是必须有 cls 这个参数。
在类方法中,能够访问类属性,但是不能访问实例属性。

与一般方法的区别:
静态方法和类方法都可以通过实例来调用,即绑定实例。
也可以通过类来调用,即 类名.方法名() 这样的形式。
而一般方法必须通过绑定实例调用。

参考

更多关于静态方法和类方法的讲解可以参考以下文章:

原文地址:https://www.cnblogs.com/id88/p/14210846.html