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

018: class, objects and instance: static method

时间:2016-01-24 22:20:42      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:

静态方法

使用@staticmethod来标记,该方法与某一个class或者某一个实例无关系,但可以用类名或者实例来调用,实际上这种写法应该一般只是为了组织代码。

实例方法的调用需要一个实例,声明时需要用self参数,调用时隐式传入该实例

类的方法调用需要一个类,其实该类本质上也是一个对象,声明时需要class参数,调用时隐式传入该类

静态方法调用不需要实实例也不需要类,其实该方法本质上与该类毫无关系,唯一的关系就是名字会该类有些关系, 用途应该只是为了组织一些代码,本质上和面向对象无关

 

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
    @staticmethod
    def display():

        print("\n*******************************")
        print("this is a static method")
        print("===============================\n")


book = Book("Python Basic", 25)

Book.display()        
book.display()

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

执行结果:

*******************************
this is a static method
===============================


*******************************
this is a static method
===============================


*******************************
<class method essence>
<function Book.display at 0x01F85108>
<function Book.display at 0x01F85108>
===============================

 

018: class, objects and instance: static method

标签:

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

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