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

    静态方法

    使用@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("
    *******************************")
            print("this is a static method")
            print("===============================
    ")
    
    
    book = Book("Python Basic", 25)
    
    Book.display()        
    book.display()
    
    print("
    *******************************")
    print("<static method essence>")
    print(Book.display)
    print(book.display)
    print("===============================
    ")

    执行结果:

    *******************************
    this is a static method
    ===============================
    
    
    *******************************
    this is a static method
    ===============================
    
    
    *******************************
    <class method essence>
    <function Book.display at 0x01F85108>
    <function Book.display at 0x01F85108>
    ===============================
  • 相关阅读:
    -_-#【H5】meta / href
    -_-#【CSS3】CSS3 gradient transition with background-position
    ♫【jQuery】detach
    -_-#setTimeout与setInterval
    -_-#【Mac】MacVim
    -_-#【jQuery】data
    ♫【Backbone】this
    -_-#【Better JS Code】严格模式
    ♫【Node】module.filename / __filename / __dirname / process.cwd() / require.main.filename
    【图片处理】ImageMagick, gm
  • 原文地址:https://www.cnblogs.com/jcsz/p/5156080.html
Copyright © 2011-2022 走看看