成员访问:__len__() & __getitem__() & __dict__

1、__len__()

  例:返回对象的实例

class A:
    def __init__(self,*args):
        self.name = args
        pass

    def __len__(self):
        return len(self.name)

a = A("32","asda",435)
print(len(a))
# 3

 2、__getiem()__

  凡是在类中定义了这个方法,那么它的实例对象(p),可以像p[key]取值,当实例对象做p[key]运算时,会调用__getitem__()方法。

class DataBase:
    def __init__(self, id, address):
        self.id = id
        self.address = address
        self.dic = {self.id: 1,
                  self.address: "192.168.1.1",
                  }

    def __getitem__(self, key):
        # return self.__dict__.get(key, "100")
        return self.dic.get(key, "default")

data = DataBase(1, "192.168.2.11")
print(data["hi"]) #default
print(data[data.id]) #1
print(data[data.address]) #192.168.1.1

3、__dict__

 Python一切皆对象,那么Python是如何管理对象的呢?

 3.1、的__dict__属性和类对象的__dict__

 1 # -*- coding: utf-8 -*-
 2 class A(object):
 3     a = 0
 4     b = 1
 5 
 6     def __init__(self):
 7         self.a = 2
 8         self.b = 3
 9 
10     def test(self):
11         print("a normal func.")
12 
13     @staticmethod
14     def static_test(self):
15         print("a static func.")
16 
17     @classmethod
18     def class_test(self):
19         print("a calss func.")
20 
21 obj = A()
22 print(A.__dict__)
23 print(obj.__dict__)
24 
25 {'__module__': '__main__', 'a': 0, 'b': 1, '__init__': <function A.__init__ at 0x00000000022A3488>, 'test': <function A.test at 0x00000000022A3A60>, 'static_test': <staticmethod object at 0x00000000022A8CC0>, 'class_test': <classmethod object at 0x00000000022A8C88>, '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None}
26 {'a': 2, 'b': 3}

  由此可见,的普通函数、静态函数、类函数、全局变量以及一些内置属性都是放在类__dict__里的

  对象的__dict__中存储了一些self.xxx的一些东西

  3.2、Python里什么没有__dict__属性

  虽然说一切皆对象,但对象也有不同,就好比不是每个人的女朋友都是一个人一样,一些内置的数据类型是没有__dict__属性的,如下

1 num = 3
2 ll = []
3 dd = {}
4 print(num.__dict__)
5 print(ll.__dict__)
6 print(dd.__dict__)
7 AttributeError: 'int' object has no attribute '__dict__'
8 AttributeError: 'list' object has no attribute '__dict__'
9 AttributeError: 'dict' object has no attribute '__dict__'

  当我们运行这样的代码时,解释器会报错。

  int、list、dict等这些常用的数据类型是没有__dict__属性的,其实这是可预料的,就算给它们__dict__属性也没啥用,毕竟它们只是用来做数据容器的。

 3.3、发生继承时的__dict__属性

  子类也有自己的__dict__,分类==父类也有自己的__dict__,父类的全局变量和函数放在父类的dict中,子类的放在子类中。

 1 # -*- coding: utf-8 -*-
 2 class Parent(object):
 3     a = 0
 4     b = 1
 5     def __init__(self):
 6         self.a = 2
 7         self.b = 3
 8     def c_test(self):
 9         pass
10 
11 class Child(Parent):
12     a = 4
13     b = 5
14     def __init__(self):
15         super(Child, self).__init__() #调用父类的构造函数
16         # self.a = 6
17         # self.b = 7
18 
19     def d_test(self):
20         pass
21     def e_test(self):
22         pass
23 
24 p = Parent()
25 c = Child()
26 print(Parent.__dict__)
27 print(Child.__dict__)
28 print(id(p.__dict__))
29 print(id(c.__dict__))
30 
31 {'__module__': '__main__', 'a': 0, 'b': 1, '__init__': <function Parent.__init__ at 0x0000000002543A60>, 'c_test': <function Parent.c_test at 0x000000000363E268>, '__dict__': <attribute '__dict__' of 'Parent' objects>, '__weakref__': <attribute '__weakref__' of 'Parent' objects>, '__doc__': None}
32 {'__module__': '__main__', 'a': 4, 'b': 5, '__init__': <function Child.__init__ at 0x000000000561D1E0>, 'd_test': <function Child.d_test at 0x000000000561D158>, 'e_test': <function Child.e_test at 0x000000000561D268>, '__doc__': None}
33 31014416
34 37386640

  父类的全局变量和函数放在父类的dict中,子类的放在子类中。父子类对象也分别有自己的dict,存储self.xxx信息。


 参考1:Python __dict__属性详解


 

posted @ 2020-07-09 15:52  小吴的日常  阅读(150)  评论(0)    收藏  举报