Python vars() Built in Function

The vars() function in Python is a built-in function that returns the dict attribute of an object. The dict attribute is a dictionary that contains all the attributes and values of an object.

Here are some examples of using the vars() function:

# Example 1: Getting the __dict__ attribute of a class object
class Person:
    name = "John"
    age = 36
    country = "Norway"


x = vars(Person)
print(x)
# Output: {'name': 'John', 'age': 36, 'country': 'Norway'}

# Example 2: Getting the __dict__ attribute of an instance object
class Fruit:
    def __init__(self, apple=5, banana=10):
        self.apple = apple
        self.banana = banana


eat = Fruit()
y = vars(eat)
print(y)
# Output: {'apple': 5, 'banana': 10}

If you have any questions about this code, you can drop a line in comment.

Comments

Popular posts from this blog

Python chr() Built in Function

Stock Market Predictions with LSTM in Python

Collections In Python

Python Count Occurrence Of Elements

Python One Liner Functions