23. 面向对象-特殊方法

一、类的特殊成员

1、doc - 表示类的描述信息

class Demo(object):
    """
    我是一个描述,可以通过__doc__来调用
    """

    def func(self):
        pass

demo = Demo
print(demo.__doc__)

>我是一个描述,可以通过__doc__来调用

2、del- 析构方法

​ 析构方法,当对象在内存中被释放时,自动触发执行。注:此方法一般无须定义,因为Python是一门高级语言,程序员在使用时无需关心内存的分配和释放,因为此工作都是交给Python解释器来执行,所以,析构函数的调用是由解释器在进行垃圾回收时自动触发执行的

3、call

​ 对象后面加括号,触发执行。注:构造方法的执行是由创建对象触发的,即:对象 = 类名() ;而对于 call 方法的执行是由对象后加括号触发的,即:对象() 或者 类()()

class Demo(object):
    def __init__(self):
        print("running")

    def __call__(self, *args, **kwargs):
        print("__call__ is running")


# 执行__init__
demo = Demo()
# 执行__call__
demo()

4、dict- 查看类或对象的所有成员

class Demo3:
    author = 'GPF'

    def __init__(self, name, count):
        self.name = name
        self.count = count

    def func(self, *args, **kwargs):
        print('func')


# 获取类的成员,即:静态字段、方法、
print(Demo3.__dict__)
>{'__init__': <function Demo3.__init__ at 0x000002680D43F6A8>, '__dict__': <attribute '__dict__' of 'Demo3' objects>, 'func': <function Demo3.func at 0x000002680D43F730>, 'author': 'GPF', '__module__': '__main__', '__weakref__': <attribute '__weakref__' of 'Demo3' objects>, '__doc__': None}

# 获取对象 demo3 的成员
demo3 = Demo3('xima', 10000)
print(demo3.__dict__)
>输出:{'count': 10000, 'name': 'xima'}

# 获取对象 demo31 的成员
demo31 = Demo3('jj', 5222)
print(demo31.__dict__)
> 输出:{'count': 5222, 'name': 'jj'}

5、str/repr()

​ 对实例使用repr()时调用。str()和repr()都是返回一个代表该实例的字符串,主要区别在于: str()的返回值要方便人来看,而repr()的返回值要方便计算机看。

__str__如果一个类中定义了__str__方法,那么在打印 对象 时,默认输出该方法的返回值。

class Demo(object):
    def __str__(self):
        return "this is String func"

demo = Demo()
print(demo)
> this is String func
class Test:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __repr__(self):
        return "Class_Test[name=" + self.name + ",age=" + str(self.age)+"]"


test = Test("TOM", 90)
print(test)

> Class_Test[name=TOM,age=90]

6、getitem、setitem、delitem

用于索引操作,如字典。以上分别表示获取、设置、删除数据

class Demo(object):
    def __getitem__(self, key):
        print("__getitem__", key)

    def __setitem__(self, key, value):
        print("__setitem__", key, value)

    def __delitem__(self, key):
        print("__delitem__", key)


demo = Demo()
# 自动触发__getitem__
result = demo["keyOne"]
demo["keyTwo"] = "GPD"
del demo["keyOne"]

>__getitem__ keyOne
>__setitem__ keyTwo GPD
>__delitem__ keyOne

7、new和metaclass

class Foo(object):
    def __init__(self):
        pass

obj = Foo()

print(type(obj))
print(type(Foo))
> <class '__main__.Foo'>
> <class 'type'>

8、上下文管理

class Point:
    def __init__(self):
        print("init------")

    def __enter__(self):
        print("enter-----")
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print(1,exc_type)
        print(2,exc_val)
        print(3,exc_tb)
        print("exit-----")
        return "a"

with Point() as p:
    print("in with-----")
    raise Exception("error")
    print("with over")


print("执行完成")

>init------
>enter-----
>in with-----
>1 <class 'Exception'>
>2 error
>3 <traceback object at 0x0000022563581208>
>exit-----
>执行完成
有3个参数如果没有异常,3个参数的值都为None,如果有异常,参数意义如下:

__exit__(self,exc_type,exc_value,exc_tb) 
(1)exc_type #异常类型
(2)exc_value #异常的值
(3)exc_tb #异常的追踪信息
(4)返回值:等效True的值为压制异常;否则,继续抛出异常
原文地址:https://www.cnblogs.com/hq82/p/12611757.html