• Python 面向对象4-特殊成员


    1.__call__

      类后面加()表示对象,执行__init__方法,对象后面加()执行__call__方法

    class Foo:
    
        def __init__(self,name):
            self.name = name
            print ("init func")
    
        def __call__(self):
            print ("call func")
    
    obj = Foo("Alex")
    obj()

    如果不定义__call__方法,那么执行obj()报错:

    TypeError: 'Foo' object is not callable

    如果定义了__call__方法,那么在对象后面加()则执行__call__方法。

    2.__str__

      有一段代码如下:

    class Foo:
    
        def __init__(self,name):
            self.name = name
            print ("init func")
    
        def __call__(self):
            print ("call func")
    # class Bar(Foo):
    #
    #     def f3(self):
    #         print (self.name)
    
    obj = Foo("Alex")
    print (obj)
    结果:
      <__main__.Foo object at 0x013349B0>

    我们想打印一个对象(obj)的内容,但是返回了一个类的内存地址,通过__str__方法可以实现这样的需求

    class Foo:
    
        def __init__(self,name):
            self.name = name
    
        def __call__(self):
            print ("call func")
    
        def __str__(self):
            return self.name
    
    obj = Foo("Alex")
    print (obj)
    结果:
      Alex

    如果__init__方法中有多个字段,那么也可以利用字符串的拼接将结果返回回来

    class Foo:
    
        def __init__(self,name,age):
            self.name = name
            self.age = age
    
        def __call__(self):
            print ("call func")
    
        def __str__(self):
            return "%s - %s" %(self.name,self.age)
    
    obj = Foo("Alex",18)
    print (obj)
    结果:
      Alex - 18
    
    
    class Foo:

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

    def __call__(self):
    print ("call func")

    # def __str__(self):
    # return "%s - %s" %(self.name,self.age)

    obj = Foo("Alex",18)
    # print (obj)
    ret = str(obj)
    print (ret)
    结果:
      <__main__.Foo object at 0x01D7F810>

    如果没有__str__方法,那么str(返回)的类对象的内存地址,如果定义了__str__方法,在执行str(obj)的时候,自动调用__str__方法。

    class Foo:
    
        def __init__(self,name,age):
            self.name = name
            self.age = age
    
        def __call__(self):
            print ("call func")
    
        def __str__(self):
            return "%s - %s" %(self.name,self.age)
    
    obj = Foo("Alex",18)
    # print (obj)
    ret = str(obj)
    print (ret)
    结果:
      Alex - 18

    3.__add__ 

    class Foo:
    
        def __init__(self,name,age):
            self.name = name
            self.age = age
    
        def __call__(self):
            print ("call func")
    def __add__(self, other):
            return "%s - %s" %(self.name,other.age)
    obj1 = Foo("Alex",18)
    obj2 = Foo("Lily",15)
    
    ret = obj1 + obj2
    print (ret)
    结果:
      Alex - 15

    __add__方法是对两个对象之间做加法,在做加法的时候系统自己调用该方法。

    4.__dict__

      

    __author__ = 'Alex'
    #coding:utf-8
    
    class Foo:
    
        def __init__(self,name,age):
            self.name = name
            self.age = age
    
        def __call__(self):
            print ("call func")
    
        # def __str__(self):
        #     return "%s - %s" %(self.name,self.age)
    
        def __add__(self, other):
            return "%s - %s" %(self.name,other.age)
    obj1 = Foo("Alex",18)
    obj2 = Foo("Lily",15)
    
    print (obj1.__dict__)
    print (obj2.__dict__)
    print (Foo.__dict__)
    结果:
      

      {'age': 18, 'name': 'Alex'}
      {'age': 15, 'name': 'Lily'}
      {'__init__': <function Foo.__init__ at 0x013641E0>, '__doc__': None, '__module__': '__main__', '__call__': <function Foo.__call__ at 0x01364228>, '__add__': <function Foo.__add__ at 0x013640C0>, '__dict__': <attribute '__dict__' of 'Foo' objects>, '__weakref__': <attribute '__weakref__' of 'Foo' objects>}

    5.__getitem__、__setitem__、__delitem__

    class Foo:
    
        def __init__(self,name,age):
            self.name = name
            self.age = age
    
        def __call__(self):
            print ("call func")
    
        # def __str__(self):
        #     return "%s - %s" %(self.name,self.age)
    
        def __add__(self, other):
            return "%s - %s" %(self.name,other.age)
    
        def __getitem__(self, item):
            return item
    
        def __setitem__(self, key, value):
            pass
    
        def __delitem__(self, key):
            pass
    
    obj1 = Foo("Alex",18)
    
    ret = obj1['aaa']
    print (ret)
    
    obj1['bbb'] = 456
    ret1 = obj1['bbb']
    print (ret1)
    
    del obj1['bbb']
    print (obj1['bbb'])

    对象的切片访问形式,例如obj1[1:4]

    
    
    class Foo:

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

    def __call__(self):
    print ("call func")

    # def __str__(self):
    # return "%s - %s" %(self.name,self.age)

    def __add__(self, other):
    return "%s - %s" %(self.name,other.age)

    def __getitem__(self, item):
    if type(item) is str:
    print (item)
    return item
    else:
    print (item.start)
    print (item.stop)
    print (item.step)


    def __setitem__(self, key, value):
    print (key.start)
    print (key.stop)
    print (key.step)
    print (type(key),type(value))


    def __delitem__(self, key):
    print (type(key))
    print (key.start)
    print (key.stop)
    print (key.step)

    obj1 = Foo("Alex",18)
    # ret = obj1['aaa']
    # ret = obj1[1:4:2]
    # obj1[1:4] = [11,22,33,44,55,66]
    del obj1[1:4]
    # print (ret)
    # print (ret)
    #
    # obj1['bbb'] = 456
    # ret1 = obj1['bbb']
    # print (ret1)
    #
    # del obj1['bbb']
    # print (obj1['bbb'])

    6.__iter__

    class Foo:
    
        def __iter__(self):
            return iter([11,22,33])
    
    
    obj = Foo()
    for item in obj:
        print (item)
    结果:
      11
      22
      33

    如果一个对象可以被迭代,那么就可以执行for循环。被循环的对象默认调用__iter__方法,返回值必须是一个可以被迭代的对象。

    class Foo:
    
        def __iter__(self):              #生成器生成一个可迭代的对象
            yield 11
            yield 22
    
    
    obj = Foo()
    for item in obj:
        print (item)
    结果:
      11
      22
  • 相关阅读:
    题目
    先贤祠3
    先贤祠2
    先贤祠1
    论文他引次数及ESI高被引论文查询方法
    [唐诗]古风(其三十一)-李白
    [唐诗]古风(其二十四)-李白
    [唐诗]古风(其十九)-李白
    [唐诗]古风(其十五)-李白
    [唐诗]古风(其三)-李白
  • 原文地址:https://www.cnblogs.com/python-study/p/5737117.html
Copyright © 2020-2023  润新知