python __dict__

類的__dict__屬性和類對象的__dict__屬性

class A(object):
	a = 0
	b = 1

	def __init__(self):
		self.a = 2
		self.b = 3

	def test(self):
		return "A"

	@staticmethod
	def static_test():
		print("static_test")

	@classmethod
	def class_test(self):
		print("class_test")
obj = A()
print(A.__dict__)
print(obj.__dict__)

運行結果:
{‘module’: ‘main’, ‘a’: 0, ‘b’: 1, ‘init’: <function A.init at 0x000001C659BBE620>, ‘test’: <function A.test at 0x000001C659BBE6A8>, ‘static_test’: <staticmethod object at 0x000001C659B19DA0>, ‘class_test’: <classmethod object at 0x000001C659B19E10>, ‘dict’: <attribute ‘dict’ of ‘A’ objects>, ‘weakref’: <attribute ‘weakref’ of ‘A’ objects>, ‘doc’: None}

{‘a’: 2, ‘b’: 3}

可以看出 :類的靜態函數、類函數、普通函數、全局變量以及一些內置的屬性都是放在類__dict__裏的
對象的__dict__中存儲了一些self.xxx的一些東西

什麼沒有__dict__屬性

python一些內置對象沒有__dict__ 屬性
如 數字 ,列表, 字典

num = 1
print(num.__dict__)

會報錯,說int 類型沒有__dict__ 屬性

發生繼承時候的__dict__屬性

class Parent(object):
	a = 0
	b = 1

	def __init__(self):
		self.a = 2
		self.b = 3

	def p_test(self):
		pass


class Child(Parent):
	a = 4
	b = 5

	def __init__(self):
		super(Child, self).__init__()

	def c_test(self):
		pass

	def p_test(self):
		pass


p = Parent()
c = Child()
print(Parent.__dict__)
print(Child.__dict__)
print(p.__dict__)
print(c.__dict__)
print(id(p.__dict__),id(c.__dict__),)

運行結果

{'__module__': '__main__', 'a': 0, 'b': 1, '__init__': <function Parent.__init__ at 0x0000013F9349E620>, 'p_test': <function Parent.p_test at 0x0000013F9349E6A8>, '__dict__': <attribute '__dict__' of 'Parent' objects>, '__weakref__': <attribute '__weakref__' of 'Parent' objects>, '__doc__': None}
{'__module__': '__main__', 'a': 4, 'b': 5, '__init__': <function Child.__init__ at 0x0000013F9349E730>, 'c_test': <function Child.c_test at 0x0000013F9349E7B8>, 'p_test': <function Child.p_test at 0x0000013F9349E840>, '__doc__': None}
{'a': 2, 'b': 3}
{'a': 2, 'b': 3}
1372535955248 1372565655768

內置的數據類型沒有__dict__屬性
每個類有自己的__dict__屬性,就算存着繼承關係,父類的__dict__ 並不會影響子類的__dict__
對象也有自己的__dict__屬性, 存儲self.xxx 信息,父子類對象__dict__ 不相同 (id不一樣)

一個實用例子

info_dict = {"name":"pei","phone":"16730818188"}

class User(object):
	def __init__(self,info_dict):
		self.name = info_dict.get("name")
		self.phone= info_dict.get("phone")

user = User(info_dict)
print("user",user.__dict__)

class User1(object):
	def __init__(self,info_dict):
		self.__dict__.update(info_dict)

user1 = User1(info_dict)
print("user1",user1.__dict__)

運行:
user {‘name’: ‘pei’, ‘phone’: ‘16730818188’}
user1 {‘name’: ‘pei’, ‘phone’: ‘16730818188’}

利用__dict__的特性,上面的類可以用如下的代替,代碼量大大減少
免了在__init__方法中類似於self.something = something的方法,使用自動化實例變量

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章