A brief analysis of Python instance methods, class methods and class method static methods

Release: 2023-07-25 16:09:38
forward
1220 people have browsed it

1. Foreword

Class methods can also be divided in more detail, and can be divided into class methods, instance methods and static methods.


##2. Detailed case explanation

  1. Example Method

    Normally, the methods defined in the class are instance methods by default.

Example:

class CLanguage:
    # 类构造方法,也属于实例方法
    def __init__(self):
        self.name = "百度"
        self.add = "www.baidu.com"


    # 下面定义了一个say实例方法
    def say(self):
        print("正在调用 say() 实例方法")
Copy after login

Call the say() method to implement the function.

clang = CLanguage()
clang.say()
Copy after login

Run result:

A brief analysis of Python instance methods, class methods and class method static methods

Note :

Instance methods must contain at least one self parameter, which is used to bind the instance object that calls this method.

  1. Class method

Python 类方法和实例方法相似,它最少也要包含一个参数,只不过类方法中通常将其命名为 cls,Python 会自动将类本身绑定给 cls 参数(注意,绑定的不是类对象)。所以在调用类方法时,无需显式为 cls 参数传参。

和实例方法最大的不同在于,类方法需要使用@classmethod修饰符进行修饰。

例:

class ass:
    #类构造方法,也属于实例方法
    def __init__(self):
        self.name = "百度"
        self.add = "www.baidu.com"
    #定义了一个类方法
    @classmethod
    def info(cls):
        print("正在调用类方法",cls)
Copy after login

如果没有 @classmethod,则 Python 解释器会将 fly() 方法认定为实例方法,而不是类方法。

类方法推荐使用类名直接调用。

#使用类名直接调用类方法
ass.info()
#使用类对象调用类方法
clang = ass()
clang.info()
Copy after login

运行结果:

A brief analysis of Python instance methods, class methods and class method static methods

  1. 类静态方法

静态方法定义在类这个空间(类命名空间)中,而函数则定义在程序所在的空间(全局命名空间)中。

静态方法没有类似 self、cls 这样的特殊参数,因此 Python 解释器不会对它包含的参数做任何类或对象的绑定。

静态方法需要使用@staticmethod修饰。

例:

class ass:
    @staticmethod
    def info(name, add):
        print(name, add)
Copy after login

静态方法可以使用类名,类对象两种方式进行调用。

# 使用类名直接调用静态方法
ass.info("百度1", "www.baidu.com")
# 使用类对象调用静态方法
clang = ass()
clang.info("百度2", "www.baidu.com")
Copy after login

运行结果:

A brief analysis of Python instance methods, class methods and class method static methods


三、总结

本文基于Python基础,介绍了实例方法、类方法和类方法静态方法,通过实际案例讲解了三种方法的不同用法,通过代码演示,运行效果图的展示,能够帮助读者更好的理解。

The above is the detailed content of A brief analysis of Python instance methods, class methods and class method static methods. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:Go语言进阶学习
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!