【面向对象】类的特殊成员方法

1. __doc__:表示类的描述信息

class Foo(object):

    '''
    描述信息
    '''

    def func(self):
        pass
print(Foo.__doc__)

>>>描述信息

2. __module__ 和  __class__ :

__module__ 表示当前操作的对象在哪个个模块

__class__     表示当前操作的对象的类是什么

3. __init__ :构造方法,通过类创建对象时,自动触发执行

4.__del__: 析构方法,当对象在内存中被释放时,自动触发执行

5. __call__ :对象后面加括号,触发执行

class Foo(object):

    '''
    描述信息
    '''

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

a=Foo()# 执行 __init__

a() # 执行 __call__
>>>call

6. __dict__ :查看类或对象中的所有成员 

通过类调用:打印类的所有属性,不包括实例属性

class Foo(object):
    def __init__(self,name,age):
        self.name=name
        self.age=age

    def func(self):
        print('this is a function')
        
print(Foo.__dict__)

>>>
{'__module__': '__main__', '__init__': <function Foo.__init__ at 0x02FACBB8>, 'func': <function Foo.func at 0x02FACB70>, '__dict__': <attribute '__dict__' of 'Foo' objects>, '__weakref__': <attribute '__weakref__' of 'Foo' objects>, '__doc__': None}

通过实例调用:打印所有实例属性,不包括类属性

f=Foo('q1ang',25)
print(f.__dict__)
>>>
{'name': 'q1ang', 'age': 25}

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

class Foo(object):
    def __init__(self,name,age):
        self.name=name
        self.age=age

    def __str__(self):
        print('this is a function')
        return 'return'
f=Foo('q1ang',25)
print(f)
>>>
this is a function
return

8.__getitem__、__setitem__、__delitem__:

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

class Foo(object):

    def __getitem__(self, key):#获取
        print('__getitem__', key)

    def __setitem__(self, key, value):#设置
        print('__setitem__', key, value)

    def __delitem__(self, key):#删除
        print('__delitem__', key)

obj = Foo()

result = obj['k1']  # 自动触发执行 __getitem__
obj['k2'] = 'q1ang'  # 自动触发执行 __setitem__
del obj['k1']
>>>
__getitem__ k1
__setitem__ k2 q1ang
__delitem__ k1

 9. __new__ __metaclass__:

class Foo(object):

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

f = Foo('q1ang')

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

f对象是Foo类的一个实例Foo类对象是 type 类的一个实例,即:Foo类对象 是通过type类的构造方法创建

创建类就可以有两种方式:

普通方式

class Foo(object):

def func(self):
print('hello word')

特殊方式:

def func(self):
    print('hello word')

Foo = type('Foo', (object,), {'func': func})
原文地址:https://www.cnblogs.com/q1ang/p/9074763.html