zoukankan      html  css  js  c++  java
  • 第十二章、类和对象的绑定方法及非绑定方法

    第十二章、类和对象的绑定方法及非绑定方法

    一、对象的绑定方法

    在类中没有被任何装饰器的方法就是绑定到对象的方法,这类方法专门为对象定制

    class People:
        country = 'China'
    
        def __init__(self, name):
            self.name = name
        def eat(self):
            print('%s is eating' % self.name)
    peo1 = People('nick')
    peol.eat()
    -------------------------------------------
    nick is eating    
    

    二、类的绑定方法

    @classmethod修饰的方法就是绑定到类的方法。这类方法专门为类定制。通过类名调用绑定到类的方法时,会将类本身当做参数传给类方法的第一个参数。

    class People:
        country = 'China'
    
        def __init__(self, name):
            self.name = name
        @classmethod
        def eat(cls):
            print('nick is eating' )
    People.eat()
    -------------------------------------------
    nick is eating
    

    说明:通过对象也可以调用,只是默认传递的第一个参数还是这个对象对应的类。

    三、非绑定方法

    **在类内部使用 @staticmethod 修饰的方法即为非绑定方法,这类方法和普通定义的函数没有区别,不与类或对象绑定,谁都可以调用,且没有自动传值的效果。 **

    什么时候用:如果函数体代码既不需要外部传入的类也不需要外部传入的对象,则应该将该函数定义成非绑定方法/普通函数

    class People:
        country = 'China'
    
        def __init__(self, name):
            self.name = name
        @staticmethod
        def eat():
            print('nick is eating' )
    People.eat()
    People('nick').eat()
    --------------------------------------------
    nick is eating
    nick is eating
    
  • 相关阅读:
    MathML
    Redux counterpart rematch dva
    flow
    pauseable 库
    a simple machine learning system demo, for ML study.
    react图工具集成
    SQLite
    Celery
    RabbitMQ installation
    Thunk
  • 原文地址:https://www.cnblogs.com/demiao/p/11449248.html
Copyright © 2011-2022 走看看