魔法方法

十种常用的魔法方法

__construct():构造方法,往往进行与首次调用。
__destruct():析构方法,销毁对象时调用。
__get():获取一个类中成员属性时调用。
__set():设置一个类中成员属性时调用。
__isset():检测变量是否被设置时调用。
__unset():对不可访问属性时调用。
__cal():在对象中不可访问方法时调用。
__clone():复制对象时调用。
__tosring():当类变成字符串时调用。
__debuginfo():打印所调试信息时调用。

__dict__属性可以说是一个类最常用的属性之一了,它又分为类的__dict__属性和实例的__dict__属性。
类的__dict__属性存储了类定义的所有类属性、类方法等组成的键值对,但不包括继承而来的属性和方法
实例的__dict__属性存储了所有的实例属性的键值对,如果没有就为空;__init__方法其实就是对__dict__属性的初始化赋值;

class Person(object):
    eye = 2
    hand = 2
    def __init__(self, name):
        self.name = name

    def run(self):
        print('run')

    @classmethod
    def eat(cls):
        print('eat')

if __name__ == "__main__":
    person = Person('cai')
    print(Person.__dict__)
    print(person.__dict__)

关于__str__和__repr__:

class Test(object):
    def __init__(self, world):
        self.world = world

    def __str__(self):
        return 'world is %s str' % self.world

    def __repr__(self):
        return 'world is %s repr' % self.world

t = Test('world_big')
print str(t)
print repr(t)

output:
world is world_big str
world is world_big repr
其实__str__相当于是str()方法 而__repr__相当于repr()方法。str是针对于让人更好理解的字符串格式化,而repr是让机器更好理解的字符串格式化。
其实获得返回值的方法也很好测试,在我们平时使用ipython的时候,在不使用print直接输出对象的时候,通常调用的就是repr方法,这个时候改写repr方法可以让他方便的输出我们想要知道的内容,而不是一个默认内容。

关于控制参数访问的__getattr__, setattr, delattr, getattribute:

class Test(object):
    def __init__(self, world):
        self.world = world

    def __getattr__(self, item):
        return item


x = Test('world123')
print x.world4

output:
world4

在找不到属性的情况下,正常的继承object的对象都会抛出AtrributeError的错误,通过__getattr__魔法方法改变了找不到属性时候的类的行为。输出了查找的属性的参数。

__setattr__是设置参数的时候会调用到的魔法方法,相当于设置参数前的一个钩子。每个设置属性的方法都绕不开这个魔法方法,只有拥有这个魔法方法的对象才可以设置属性。在使用这个方法的时候要特别注意到不要被循环调用了。
init
该方法可以说是类最常用的方法了,python在调用new方法后会紧接着调用init方法,我们将实例的一些初始化操作放在该方法中,即对__dict__属性进行操作;

class Person(object):

    def __init__(self, name):
        self.name = name
    def __setattr__(self, key, value):
        print(key,value)
        super().__setattr__(key,value)
if __name__ == "__main__":
    person = Person('cai')
    print(person.__dict__) # {'name': 'cai'}
    

类的常用魔法属性有__dict__,doc,mould,slots,其中slots属性需要自定义,其他属性默认存在;
构造类常用init,new,del方法,它们在类创造、初始化、销毁时触发;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值