Python 魔术方法

EN
EN
2023-04-04 / 0 评论 / 36 阅读 / 正在检测是否收录...

魔术方法

class A:
    mind = "哈哈"
    def __init__(self):
        print("A init")
        self.title = "这是A类"
    '''
    描述信息
    '''
    def funa(self):
        pass

    def __call__(self, *args, **kwargs):
        print("A call")

''' 
查看所有的魔术方法 返回一个列表
'''
print(dir(A))

'''
1. __doc__ 查看到注释内容
'''
print(A.__doc__) #>>> 描述信息

'''
2. __module__ 当前操作的对象在哪个模块
'''
a = A()
print(a.__module__) #>>> __main__
print(A.__module__) #>>> __main__

'''
3. __class__ 当前操作的对象的类是哪个
'''
print(a.__class__) #>>> <class '__main__.A'>

'''
4. __call__ 允许类能像实例一样取调用实例方法
'''
A()() # >>> A init A call
#创建实例对象
b = A()   #>>> A init
b()  #>>> A call  # 自动调用call方法

'''
5.  __dict__ 查看类或对象中的所有属性,返回一个字典
    是 dir() 的子集
'''
# 查看类的属性 方法
print(A.__dict__) #>>> {'__module__': '__main__', 'mind': '哈哈', '__init__': <function A.__init__ at 0x000001C79FF28AE0>, 'funa': <function A.funa at 0x000001C79FF2A020>, '__call__': <function A.__call__ at 0x000001C7A01289A0>, '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None}
# 查看实例对象的属性
print(a.__dict__) #>>>  {'title': '这是A类'}

'''
6. __repr__ 输出是给程序员Debug看的
   __str__ 打印实例对象时,返回自定义的字符串
'''

'''
7. __getitem__(self,key) 
   __setitem__(self,key,value) 
   __getitem__(self,key) 
'''
class B:
    def __getitem__(self, key):
        print("__getitem__",key)
    def __setitem__(self, key, value):
        print("__setitem__", key,value)
    def __delitem__(self, key):
        print("__delitem__", key)
bB = B()
bB['name'] = "张三" # 自动触发执行__setitem__ >>> __setitem__ name 张三
res = bB['name'] # 自动触发执行__getitem__ >>> __getitem__ name
del bB['name'] # 自动触发执行__delitem__ >>> __delitem__ name
0

评论 (0)

取消