码迷,mamicode.com
首页 > 其他好文 > 详细

017: class, objects and instance: class method

时间:2016-01-24 22:27:52      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:

类的方法

所谓类的方法,也就是,这个方法会绑定到一个类上面,实例化一个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("\n*******************************")
        print("this is a class method", cls.num)
        print("===============================\n")



book = Book("Python Basic", 25)

Book.display()        
book.display()

print("\n*******************************")
print("<class method essence>")
print(Book.display)
print(book.display)
print("===============================\n")

执行结果为:

*******************************
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>>
===============================

 

017: class, objects and instance: class method

标签:

原文地址:http://www.cnblogs.com/jcsz/p/5156046.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!