python3 中__dict__的用法

直接看代码吧

class Person(object):
	total = 0
	@classmethod
	def set_num(cls):
		cls.total += 1
	@classmethod
	def cls_dict(cls):
		return cls.__dict__
	@staticmethod
	def say_hello(word="world"):
		print("hello %s"%world)
	
	def __init__(self, name=None,age=None,height=None):
		self.name = name
		self.age = age
		self.height = height
		self.__class__.set_num()		
		
	def set_age(self,age):
		self.age = age

	def to_dict(self):
		return self.__dict__


person = Person("jack",23)
person2 = Person("jack",23)
person_attr_dict =  person.to_dict()

print("person.num:", person.total)
print("person_attr_dict:", person_attr_dict)
print("person_attr_dict:", person.__dict__)

print("==================")
print("Class Person_attr_dict:", Person.cls_dict())
print("==================")
print("Class Person_attr_dict:", Person.__dict__)
print("==================")
print("Class Person_attr_dict:", person.__class__.__dict__)

Sublime Text中运行结果

person.num: 2
person_attr_dict: {'name': 'jack', 'age': 23, 'height': None}
person_attr_dict: {'name': 'jack', 'age': 23, 'height': None}
==================
Class Person_attr_dict: {'__module__': '__main__', 'total': 2, 'set_num': <classmethod object at 0x000001C97EDEBE10>, 'cls_dict': <classmethod object at 0x000001C97EDEBE48>, 'say_hello': <staticmethod object at 0x000001C97EDEBE80>, '__init__': <function Person.__init__ at 0x000001C97EDF60D0>, 'set_age': <function Person.set_age at 0x000001C97EDF6158>, 'to_dict': <function Person.to_dict at 0x000001C97EDF61E0>, '__dict__': <attribute '__dict__' of 'Person' objects>, '__weakref__': <attribute '__weakref__' of 'Person' objects>, '__doc__': None}
==================
Class Person_attr_dict: {'__module__': '__main__', 'total': 2, 'set_num': <classmethod object at 0x000001C97EDEBE10>, 'cls_dict': <classmethod object at 0x000001C97EDEBE48>, 'say_hello': <staticmethod object at 0x000001C97EDEBE80>, '__init__': <function Person.__init__ at 0x000001C97EDF60D0>, 'set_age': <function Person.set_age at 0x000001C97EDF6158>, 'to_dict': <function Person.to_dict at 0x000001C97EDF61E0>, '__dict__': <attribute '__dict__' of 'Person' objects>, '__weakref__': <attribute '__weakref__' of 'Person' objects>, '__doc__': None}
==================
Class Person_attr_dict: {'__module__': '__main__', 'total': 2, 'set_num': <classmethod object at 0x000001C97EDEBE10>, 'cls_dict': <classmethod object at 0x000001C97EDEBE48>, 'say_hello': <staticmethod object at 0x000001C97EDEBE80>, '__init__': <function Person.__init__ at 0x000001C97EDF60D0>, 'set_age': <function Person.set_age at 0x000001C97EDF6158>, 'to_dict': <function Person.to_dict at 0x000001C97EDF61E0>, '__dict__': <attribute '__dict__' of 'Person' objects>, '__weakref__': <attribute '__weakref__' of 'Person' objects>, '__doc__': None}
[Finished in 0.3s]
  • 总结:
    python 中预置的__dict__属性,是保存类实例或对象实例的属性变量键值对字典
    对类中定义的方法(函数),方法名也是属性变量,绑定一个方法(函数)
  • 函数
    函数名是一个变量,它绑定的是一个函数,这个函数指的就是 (形参列表){代码块}

你可能感兴趣的:(python3)