PythonPython圈Python基础

Python10--类中的魔法方法

2020-08-29  本文已影响0人  伊洛的小屋
1.类中的特殊方法(魔法方法)

1.__init__方法是在实例对象创建完成后调用的,主要用于设置实例对象的初始值,它的第一个参数为 self,可以不需要返回值

  1. __new__方法是在实例对象被创建之前调用的,主要用于创建实例对象并返回实例对象,它的第一个参数为cls ,它只会取 cls参数,其余参数都传给了 __init__方法,必须要有返回值可以是 super().__new__(cls) 或是 object.__new__(cls)
# 作者:伊洛Yiluo 公众号:伊洛的小屋
# 个人主页:https://yiluotalk.com/
# 博客园:https://www.cnblogs.com/yiluotalk/
In [1]: class People:
   ...:     def __new__(cls, name):
   ...:         print('__new__')
   ...:         return super(People, cls).__new__(cls)
   ...:     def __init__(self, name):
   ...:         print('__init__')
   ...:         self.name = name
   ...:     def __del__(self):
   ...:         print('__del__')
   ...:

In [2]: man = People('Yiluo')
__new__
__init__

In [3]: man.name
Out[3]: 'Yiluo'

In [4]: del man
__del__

>>> class People:
...     __slots__ = ('name', 'age')
...
>>> somebody = People()
>>> somebody.name = 'Yiluo'
>>> somebody.age = 18
>>> somebody.name
'Yiluo'
>>> somebody.age
18
>>>
>>> class Man(People):
...     __slots__ = ('city')
...
>>> person = Man()

>>> person.name = 'Yiluo'
>>> person.age = 18
>>> person.address = 'shenzhen'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Man' object has no attribute 'address'
>>> person.city = 'shenzhen'
>>> person.name
'Yiluo'
>>> person.age
18
>>> person.city
'shenzhen'
2. __getattribute____getattr__
3.__call__
>>> class People:
...     pass
...
>>> person = People()
>>> callable(person)
False
>>> callable(People())
False
>>> callable(People)
True
>>>
>>> class People:
...     def __call__(self):
...         print('__call__')
...
>>> person = People()
>>> person()
__call__
>>> callable(person)
True
4.__iter____next__
#!/usr/bin/env python3

class Test:
    def __init__(self, data=0):
        self.data = data
    def __iter__(self):
        return self
    def __next__(self):
        if self.data > 5:
            raise StopIteration
        else:
            self.data += 1
            return self.data

for i in Test():
    print(i)
➜  code python3 demo.py
1
2
3
4
5
6

欢迎下方【戳一下】【点赞】
Author:伊洛Yiluo
愿你享受每一天,Just Enjoy !

上一篇 下一篇

猜你喜欢

热点阅读