代码改变世界

018: class, objects and instance: static method

2016-01-24 21:55  Miles.Yao  阅读(173)  评论(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>
===============================