52、列举面向对象中的特殊成员以及应用场景

1. __doc__  描述类的信息

class Foo(object):  
    # 单引号和双引号都可以  
    """这里描述类的信息"""  
  
    def func(self):  
        pass  
  
print(Foo.__doc__

显示的结果:

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

# __call__方法的执行是由对象加括号触发的,即:对象()或者 类()()  
class Foo(object):  
    def __call__(self, *args, **kwargs):  
        print("running call", args, kwargs)  
  
foo = Foo()  
foo(1, 2, 3, name = "UserPython"  
  
Foo()(1, 2, 3, name = "UserPython"

显示的结果:

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

class Foo(object):  
    def __init__(self, name, age):  
        self.name = name  
        self.age = age  
  
foo = Foo("UserPython", 17)  
  
print(Foo.__dict__#打印类里的所有属性,不包括实例属性  
print(foo.__dict__#打印所有实例属性,不包括类属性

显示的结果:

{'__weakref__': <attribute '__weakref__' of 'Foo' objects>, '__init__': <function Foo.__init__ at 0x0000000000BB0730>, '__dict__': <attribute '__dict__' of 'Foo' objects>, '__module__': '__main__', '__doc__': None}
{'name': 'UserPython', 'age': 17}

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

class Foo(object):  
    def __init__(self, name, age):  
        self.name = name  
        self.age = age  
  
    def __str__(self):  
        return "<obj:%s>" % self.name  
  
foo = Foo("UserPython", 17)  
  
print(foo) #>>><obj:UserPython>

显示的效果为:

<obj:UserPython>

 5. __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)  
  
foo = Foo()  
foo["name"] = "UserPython" #>>>__setitem__ name UserPython  触发__setitem__  
foo["name"#>>>__getitem__ name  触发__getitem__  
del foo["name"#>>>__delitem__ name  触发__delitem__

显示的结果为:

6. __new____metaclass__

class Foo(object):  
  
    def __init__(self, name):  
        self.name = name  
  
foo = Foo("UserPython")  
''''' 
上述代码中,foo是通过Foo类实例化的对象,其实,不仅foo是一个对象,Foo类本身也是一个对象,因为在Python中一切事物都是对象。 
如果按照一切事物都是对象的理论:foo对象时通过执行Foo类的构造方法创建,那么Foo类对象应该也是通过执行某个类的构造方法创建。 
'''  
  
print(type(foo)) 
print(type(Foo)) 
# 所以,foo对象是Foo类的一个实例,Foo类对象是type类的一个实例,即:Foo类对象是通过type类的构造方法创建。那么,创建类就可以有两种方式了

显示的结果为:

# 普通方式  
class Foo(object):  
    def func(self):  
        print("hello UserPython")
# 特殊方式  
def func(self):  
    print("hello %s" % self.name)  
  
def __init__(self, name, age): #构造方法  
    self.name = name   
    self.age = age  
  
# 创建了一个type类,然后用type类实例化了一个Foo类,由于Foo本身是一个类,所以Foo又实例化了一个对象foo  
Foo = type('Foo', (object, ), {"func" : func,  "__init__" : __init__})  
  
foo = Foo("UserPython", 19)  
  
foo.func()  
  
print(type(Foo))

显示的结果为:

 

原文地址:https://www.cnblogs.com/zhuifeng-mayi/p/9226185.html