zoukankan      html  css  js  c++  java
  • 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'>>
    ===============================
  • 相关阅读:
    查缺补漏中~~
    The number of divisors(约数) about Humble Numbers
    Octorber 21st
    素数回文
    盐水的故事
    居然因为交换错了好几把。。。。,还有坑点是num1可以大于num2
    税收与补贴问题(洛谷1023)
    斐波拉契高精度(洛谷1255)
    高精度模板
    Codeforces#373 Div2
  • 原文地址:https://www.cnblogs.com/jcsz/p/5156046.html
Copyright © 2011-2022 走看看