在python中有一些方法被称之为魔法方法,在对对象进行操作的时候会自动调用。

doc

  • 查看说明文档 ```python class FirstClass(object): “””我是说明文档””” pass

print(FirstClass.doc)

  1. ![image.png](https://cdn.nlark.com/yuque/0/2020/png/1325594/1594452972542-a3baaf0c-ed30-46f2-bb4d-6cf396b2fabc.png#align=left&display=inline&height=125&margin=%5Bobject%20Object%5D&name=image.png&originHeight=160&originWidth=1408&size=43202&status=done&style=none&width=1100)
  2. <a name="puBgT"></a>
  3. ####
  4. <a name="PH6au"></a>
  5. #### __mudule__
  6. - 查看类所属模块
  7. - 从下代码结果可以知道,FirstClassmain主程序中
  8. - 如果是从别的模块导入,如下所示从pandas导入的DataFrame类属于pandas.core.frame模块
  9. ```python
  10. import pandas as pd
  11. class FirstClass(object):
  12. """我是说明文档"""
  13. pass
  14. print(FirstClass.__module__)
  15. print(pd.DataFrame.__module__)

image.png

class

  • 查看对象属于什么类,如下,FirstClass属于type类 ```python class FirstClass(object): “””我是说明文档””” pass

print(FirstClass.class)

  1. ![image.png](https://cdn.nlark.com/yuque/0/2020/png/1325594/1594453399017-1a49c155-7594-4b99-b2ee-e75c26bf5693.png#align=left&display=inline&height=63&margin=%5Bobject%20Object%5D&name=image.png&originHeight=75&originWidth=1307&size=39822&status=done&style=none&width=1100)
  2. <a name="z21jQ"></a>
  3. ####
  4. <a name="yC80f"></a>
  5. #### __call__
  6. - 使类的实例化可以被调用
  7. ```python
  8. class FirstClass(object):
  9. pass
  10. first = FirstClass()
  11. first()

image.png

  1. class FirstClass(object):
  2. def __call__(self):
  3. return 666
  4. first = FirstClass()
  5. print(first())

image.png

newinit

  • new方法用于继承基类的时候创建子类
  • init方法用于实例化的时候初始化方法

    • 如下所示,实例化的时候先调用了new方法,传入的cls表示FirstClass本身
    • 然后初始化了self.phone属性,传入的self表示实例对象本身
    • first这个对象属于tuple类 ```python class FirstClass(tuple): def new(cls): print(“我要创建一个tuple类!!!”) return super().new(cls)

      def init(self): print(“我要初始化一个tuple实例!!”) self.phone = 110

first = FirstClass() print(isinstance(first, tuple)) print(first.phone)

  1. ![image.png](https://cdn.nlark.com/yuque/0/2020/png/1325594/1594454335202-672f479a-ce7d-4000-9247-c2fd8ec96a09.png#align=left&display=inline&height=86&margin=%5Bobject%20Object%5D&name=image.png&originHeight=105&originWidth=1340&size=39375&status=done&style=none&width=1100)
  2. <a name="m4Xty"></a>
  3. #### __del__
  4. - 在对象被回收或者删除的时候自动调用,又成为析构方法
  5. ```python
  6. class FirstClass(tuple):
  7. def __new__(cls):
  8. print("我要创建一个tuple类!!!")
  9. return super().__new__(cls)
  10. def __init__(self):
  11. print("我要初始化一个tuple实例!!")
  12. self.phone = 110
  13. def __del__(self):
  14. print("我要被干掉了!!!")
  15. first = FirstClass()

image.png

str

  • 返回打印值 ```python import datetime

class Student: def init(self, date): self.date = date

  1. def __str__(self):
  2. # 可读性
  3. return self.date
  4. def __repr__(self):
  5. # 维护性
  6. return self.date

s = Student(datetime.datetime.now()) print(s) ``` image.png