vars is one of the built-in Python functions. It is mainly used to return the object's __dict__ attribute, which is a dictionary that contains all the attributes and attribute values of the object. The vars function is very useful when debugging and checking object state. This article will introduce in detail the usage of the vars function, including its basic syntax, application scenarios and specific sample code, to help you fully master this practical tool.
Basic syntax
The basic syntax of the vars function is as follows:
vars([object])
object: Optional parameter. If an object is provided, vars returns the __dict__ property of that object. If no argument is provided, a local variable dictionary of the current scope is returned.
Example
class Person: def __init__(self, name, age): = name = age p = Person("Alice", 30) print(vars(p))
In this example, vars(p) returns a dictionary of attributes for Person object p:
{'name': 'Alice', 'age': 30}
Use scenarios
Check the properties and methods of an object
The vars function can be used to check all properties and methods of an object, especially when debugging.
class Car: def __init__(self, make, model, year): = make = model = year my_car = Car("Toyota", "Camry", 2020) print(vars(my_car))
Output:
{'make': 'Toyota', 'model': 'Camry', 'year': 2020}
Modify the properties of the object
The dictionary returned by the vars function can be directly modified.
class Car: def __init__(self, make, model, year): = make = model = year my_car = Car("Toyota", "Camry", 2020) car_dict = vars(my_car) car_dict['year'] = 2021 print(vars(my_car))
Output:
{'make': 'Toyota', 'model': 'Camry', 'year': 2021}
Get local variables in the current scope
If no arguments are provided, the vars function returns the local variable dictionary of the current scope.
def example(): a = 10 b = 20 print(vars()) example()
Output:
{'a': 10, 'b': 20}
Relationship with __dict__ attribute
The vars function actually returns the __dict__ property of the object. You can also directly access the __dict__ attribute to get the same result.
class Person: def __init__(self, name, age): = name = age p = Person("Alice", 30) print(p.__dict__) print(vars(p))
The outputs of both are the same:
{'name': 'Alice', 'age': 30}
Specific examples
Dynamically add attributes
The vars function can be used to dynamically add properties to objects.
class DynamicAttributes: pass obj = DynamicAttributes() attributes = vars(obj) attributes['new_attr'] = 'I am new here!' print(vars(obj))
Output:
{'new_attr': 'I am new here!'}
Debugging complex objects
When debugging complex objects, the vars function can help us quickly view the current state of the object.
class Employee: def __init__(self, id, name, position): = id = name = position = { 'department': 'Sales', 'location': 'New York' } emp = Employee(1, 'John Doe', 'Manager') print(vars(emp))
Output:
{'id': 1, 'name': 'John Doe', 'position': 'Manager', 'details': {'department': 'Sales', 'location': 'New York'}}
Modify attribute dictionary
The dictionary returned by the vars function can not only view the properties of the object, but also directly modify them.
class Book: def __init__(self, title, author): = title = author b = Book('1984', 'George Orwell') book_dict = vars(b) book_dict['author'] = 'Orwell' print(vars(b))
Output:
{'title': '1984', 'author': 'Orwell'}
Relationship with class variables
The dictionary returned by the vars function only includes instance variables and does not include class variables.
class MyClass: class_var = 'Class Variable' def __init__(self, instance_var): self.instance_var = instance_var obj = MyClass('Instance Variable') print(vars(obj)) # Contains only instance variablesprint(MyClass.__dict__) # Contains class variables
Output:
{'instance_var': 'Instance Variable'}
{'__module__': '__main__', 'class_var': 'Class Variable', '__init__': <function MyClass.__init__ at 0x7f3f9c0d0d30>, '__dict__': <attribute '__dict__' of 'MyClass' objects>, '__weakref__': <attribute '__weakref__' of 'MyClass' objects>, '__doc__': None}
Summarize
This article introduces in detail the usage of the vars function in Python, including its basic syntax, usage scenarios and specific sample code. The vars function is used to return the object's __dict__ attribute, which helps to view and modify all attributes and attribute values of the object. The vars function is very useful when debugging and checking object state. The article shows how to use the vars function to check the properties and methods of an object, modify the properties of an object, dynamically add properties, and obtain local variables in the current scope through multiple examples. Mastering the use of vars functions can handle object properties and debug code more efficiently in Python programming.
The above is the detailed content of Python using vars to easily obtain object properties. For more information about Python vars to obtain object properties, please follow my other related articles!