zoukankan      html  css  js  c++  java
  • 017: class, objects and instance: class method

    类的方法

    所谓类的方法,也就是,这个方法会绑定到一个类上面,实例化一个instance的时候,这个方法不会再重新生成 一份,它只有访问类级别的变量

    它用@classmethod标签来标注这是一个class method.

    class Book(object):
        num = 10
        # instance method, will be bound to an object
        def __init__(self, title, price):
            self.title = title
            self.price = price
        
        # class method, will not be bound to an object
        @classmethod
        def display(cls):
    
            print("
    *******************************")
            print("this is a class method", cls.num)
            print("===============================
    ")
    
    
    
    book = Book("Python Basic", 25)
    
    Book.display()        
    book.display()
    
    print("
    *******************************")
    print("<class method essence>")
    print(Book.display)
    print(book.display)
    print("===============================
    ")

    执行结果为:

    *******************************
    this is a class method 10
    ===============================
    
    
    *******************************
    this is a class method 10
    ===============================
    
    
    *******************************
    <class method essence>
    <bound method type.display of <class '__main__.Book'>>
    <bound method type.display of <class '__main__.Book'>>
    ===============================
  • 相关阅读:
    Python使用inspect查看代码参数
    Python的hasattr() getattr() setattr()
    Module-GitBook使用手册
    Module-Hadoop技术文档
    Module-Git使用手册
    Module-Faker使用手册
    Module-Docker使用手册
    Module-DB2技术文档
    Module-Dask并行任务调度
    Module-Apache使用说明
  • 原文地址:https://www.cnblogs.com/jcsz/p/5156046.html
Copyright © 2011-2022 走看看