zoukankan      html  css  js  c++  java
  • Python中的三个特殊函数

    __call__类似C++中function object。可以把对象当做函数使用。

    示例代码如下:

    class Animal:
        def __init__(self, name, legs):
            self.name = name
            self.legs = legs
            self.stomach = []
            
        def __call__(self, food):
            self.stomach.append(food)
            
        def poop(self):
            if len(self.stomach) > 0:
                return self.stomach.pop(0)
            
        def __str__(self):
            return 'A animal named {0}'.format(self.name)
    
    cow = Animal('king', 4)
    dog = Animal('flopp', 4)
    print('We have 2 animals a cow named {0} and dog named {1}, 
    both have {2} legs.'.format(cow.name, dog.name, cow.legs))
    
    print(cow)
    print(dog)
    
    cow('gras')
    print(cow.stomach)
    
    dog('bone')
    dog('beef')
    print(dog.stomach)
    
    print(cow.poop())
    print(cow.stomach)

    该代码片段的输出:

    We have 2 animals a cow named king and dog named flopp, both have 4 legs.
    A animal named king
    A animal named flopp
    ['gras']
    ['bone', 'beef']
    gras
    []

    __new__是一个静态函数,并且至少需要传递一个参数cls。cls表示需要实例化的类。此参数在实例化时由Python解释器自动提供。另外,实例化对象时,__new__在__init__方法之前调用。有个比较形象化的比喻:__new__方法就是前期的原材料购买环节,__init__方法就是在有原材料的基础上,加工、初始化商品环节。

    运行以下实例代码能加深此函数的理解:

    class Demo(object): 
      def __init__(self): 
        print('__init__() called...')
    
      def __new__(cls, *args, **kwargs): 
        print('__new__() - {cls}'.format(cls=cls) )
        return object.__new__(cls, *args, **kwargs) 
    
    if __name__ == '__main__': 
      de = Demo() 

    此段代码的输出如下:

    __new__() - <class '__main__.Demo'>
    __init__() called...

    以下是标准文档的摘录:

    __call__:

    Called when the instance is “called” as a function; if this method is defined, x(arg1, arg2, ...) is a shorthand for x.__call__(arg1, arg2, ...).

     

    __new__:

    Called to create a new instance of class cls. __new__() is a static method (special-cased so you need not declare it as such) that takes the class of which an instance was requested as its first argument. The remaining arguments are those passed to the object constructor expression (the call to the class). The return value of __new__() should be the new object instance (usually an instance of cls).

     

    __init__:

    Called after the instance has been created (by __new__()), but before it is returned to the caller. The arguments are those passed to the class constructor expression. If a base class has an __init__() method, the derived class’s __init__() method, if any, must explicitly call it to ensure proper initialization of the base class part of the instance; for example: super().__init__([args...]).

     

    另外有一个值得注意的函数,该函数在把对象当做字符串使用时调用。

    __str__:

    Called by str(object) and the built-in functions format() and print() to compute the “informal” or nicely printable string representation of an object. The return value must be a string object.

     

  • 相关阅读:
    sql server 2000系统表sysproperties在SQL 2008中无效的问题
    查询字段的默认值
    OBJECT_ID()的使用方法
    查询指定表的数据类型和长度
    SQL SERVER 比较两个数据库中表和字段的差异
    [再寄小读者之数学篇](2014-06-26 Logarithmical Sobolev inequality using BMO space)
    [再寄小读者之数学篇](2014-06-26 Besov space estimates)
    [再寄小读者之数学篇](2014-06-23 Bernstein's inequality)
    [再寄小读者之数学篇](2014-06-26 绝对值不等式)
    [再寄小读者之数学篇](2014-06-23 Gronwall-type inequality)
  • 原文地址:https://www.cnblogs.com/licb/p/9685019.html
Copyright © 2011-2022 走看看