在python中有一些方法被称之为魔法方法,在对对象进行操作的时候会自动调用。
doc
- 查看说明文档 ```python class FirstClass(object): “””我是说明文档””” pass
print(FirstClass.doc)
![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)
<a name="puBgT"></a>
####
<a name="PH6au"></a>
#### __mudule__
- 查看类所属模块
- 从下代码结果可以知道,FirstClass在main主程序中
- 如果是从别的模块导入,如下所示从pandas导入的DataFrame类属于pandas.core.frame模块
```python
import pandas as pd
class FirstClass(object):
"""我是说明文档"""
pass
print(FirstClass.__module__)
print(pd.DataFrame.__module__)
class
- 查看对象属于什么类,如下,FirstClass属于type类 ```python class FirstClass(object): “””我是说明文档””” pass
print(FirstClass.class)
![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)
<a name="z21jQ"></a>
####
<a name="yC80f"></a>
#### __call__
- 使类的实例化可以被调用
```python
class FirstClass(object):
pass
first = FirstClass()
first()
class FirstClass(object):
def __call__(self):
return 666
first = FirstClass()
print(first())
new和init
- 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)
![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)
<a name="m4Xty"></a>
#### __del__
- 在对象被回收或者删除的时候自动调用,又成为析构方法
```python
class FirstClass(tuple):
def __new__(cls):
print("我要创建一个tuple类!!!")
return super().__new__(cls)
def __init__(self):
print("我要初始化一个tuple实例!!")
self.phone = 110
def __del__(self):
print("我要被干掉了!!!")
first = FirstClass()
str
- 返回打印值 ```python import datetime
class Student: def init(self, date): self.date = date
def __str__(self):
# 可读性
return self.date
def __repr__(self):
# 维护性
return self.date
s = Student(datetime.datetime.now()) print(s) ```