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'>>
===============================
原文地址:https://www.cnblogs.com/jcsz/p/5156046.html