提示信息

Python __dict__

凉薄 已关注

In Python, __dict__ is a built-in attribute of an object or class that returns a dictionary containing the attributes and their values of the object or class.

For an object, __dict__ represents the instance's namespace, i.e., a dictionary containing all the instance variable names as keys and their corresponding values as values.

For a class, __dict__ represents the class's namespace, i.e., a dictionary containing all the class variable names as keys and their corresponding values as values.

Here is an example to demonstrate the usage of __dict__:

  1. class Person:
  2. def __init__(self, name, age):
  3. self.name = name
  4. self.age = age
  5. person = Person("John Doe", 25)
  6. print(person.__dict__) # Output: {'name': 'John Doe', 'age': 25}
  7. person.__dict__["gender"] = "Male"
  8. print(person.__dict__) # Output: {'name': 'John Doe', 'age': 25, 'gender': 'Male'}
  9. print(Person.__dict__) # Output: {'__module__': '__main__', '__init__': <function Person.__init__ at 0x7f91900e4950>, '__dict__': <attribute '__dict__' of 'Person' objects>, '__weakref__': <attribute '__weakref__' of 'Person' objects>, '__doc__': None}

In the above example, person.__dict__ returns a dictionary containing the attributes and values of the person object. Similarly, Person.__dict__ returns a dictionary containing the attributes and values of the Person class.

    遇到难题? "AI大模型GPT4.0、GPT" 是你的私人解答专家! 点击按钮去提问......
凉薄 关注 已关注

最近一次登录:2023-10-10 10:23:13   

暂时还没有签名,请关注我或评论我的文章
×
免费图表工具,画流程图、架构图