python入门(三十二):类的特殊成员

来源:互联网 发布:百事淘宝跟淘宝的区别 编辑:程序博客网 时间:2024/05/16 09:41

1.__init__:用来初始化实例的值.只初始化值,不要返回值

2.__del__:类似于析构函数

3.__call__

class Foo:    def __init__(self):        print('init')    def __call__(self, *args, **kwargs):        print('call')        return 1Foo()()

4.__getitem__  __setitem__  __delitem__
class Foo:    def __getitem__(self, item):        print(item)    def __setitem__(self, key, value):        print(key, value)    def __delitem__(self, key):        print(key)r = Foo()#__getitem__r['cbanba']#__setitem__r['gyc'] = 123#__delitem__del r['gyc']
5.__dict__获取类和对象存了什么
class Foo:    def __init__(self):        self.name = 'gyc'r = Foo()print(Foo.__dict__)print(r.__dict__)
{'__module__': '__main__', '__init__': <function Foo.__init__ at 0x009CC660>, '__dict__': <attribute '__dict__' of 'Foo' objects>, '__weakref__': <attribute '__weakref__' of 'Foo' objects>, '__doc__': None}
{'name': 'gyc'}
6.__iter__
class Foo:    def __iter__(self):        yield 1        yield 2        yield 3r = Foo()#如果执行for对象时,自动会执行iter方法,生成器for i in r:    print(i)
1
2
3
原创粉丝点击