The existing Person classes are as follows
class Person: name = 'Xiao Bai' def hobby(self): print('coding')
__Use of dict
Function: view properties in objects and view properties and methods in classes
per = Person() print(per.__dict__) print(Person.__dict__)
The results are as follows:
{'age': 20} {'__module__': '__main__', 'name': 'Xiao Bai', '__init__': <function Person.__init__ at 0x00000224A9B730D0>, 'hobby': <function Person.hobby at 0x00000224A9B73158>, '__dict__': <attribute '__dict__' of 'Person' objects>, '__weakref__': <attribute '__weakref__' of 'Person' objects>, '__doc__': None}
In per object, there is only age attribute, no name attribute and hobby method.
Use of dir()
Function: view properties and methods in objects and classes
per = Person(20) print(dir(per)) print(dir(Person))
The results are as follows:
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'age', 'hobby', 'name'] ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'hobby', 'name']
__Use of class
Role: view class
per = Person(20) print(per.__class__)
Execution result:
<class '__main__.Person'>
The use of setattr and getattr
setattr function: add attributes to objects
getattr function: view the corresponding properties in the object
per = Person(20) setattr(per,'facevalue',90) print(getattr(per,'facevalue')) print(per.__dict__)
Execution result:
90 {'age': 20, 'facevalue': 90}
__Use of delattr_uuuu
Function: delete the corresponding attribute in the object
per = Person(20) per.sex = 'men' print(per.__dict__) per.__delattr__('sex') print(per.__dict__)
Execution result:
{'age': 20, 'sex': 'men'} {'age': 20}