python中的__init__ 、__new__、__call__等内置函数的剖析

1.__new__(cls, *args, **kwargs)  

创建对象时调用,返回当前对象的一个实例;注意:这里的第一个参数是cls即class本身
2.__init__(self, *args, **kwargs)

创建完对象后调用,对当前对象的实例的一些初始化,无返回值,即在调用__new__之后,根据返回的实例初始化;注意,这里的第一个参数是self即对象本身【注意和new的区别】
3.__call__(self,  *args, **kwargs)

如果类实现了这个方法,相当于把这个类型的对象当作函数来使用,相当于 重载了括号运算符

#__conding:utf-8__



class Person:

    def __init__(self, name):

        self.name = name

    def sayHi(self):

        print("Hello my name is:%s" %self.name)



p = Person("wuyanlong")

p.sayHi()





class P(object):

    def __init__(self, *args, **kwargs):

        print "init"

        super(P,self).__init__(*args, **kwargs)

    def __new__(cls, *args, **kwargs):

        print "new", cls

        return super(P, cls).__new__(cls ,*args, **kwargs)

    def __call__(self, *args, **kwargs):

        print "call"



pp = P()

print "__________"

pp()

运行结果:

***:~/Python爬虫/class$ python calss1.py 

Hello my name is:wuyanlong

new <class '__main__.P'>

init

__________

call

 

4. __getattr__:

从对象中读取某个属性时,首先需要从self.__dicts__中搜索该属性,再从__getattr__中查找。

class A(object): 

    def __init__(self): 

        self.name = 'from __dicts__: zdy' 

 

    def __getattr__(self, item): 

        if item == 'name': 

            return 'from __getattr__: zdy' 

        elif item == 'age': 

            return 26 

 

a = A() 

print a.name # 从__dict__里获得的 

print a.age # 从__getattr__获得的

 

5. __setattr__

class A(object):

    def __setattr__(self, *args, **kwargs): 

        print 'call func set attr' 

        return object.__setattr__(self, *args, **kwargs) 

 

 

6. __delattr__

函数式用来删除对象的属性:

class A(object):

    def __delattr__(self, *args, **kwargs): 

        print 'call func del attr' 

        return object.__delattr__(self, *args, **kwargs)  

 

你可能感兴趣的:(python)