[Road to intermediate level] Utilize Python's built-in function vars

Link to summary

https://qiita.com/ganariya/items/fb3f38c2f4a35d1ee2e8

Introduction

In order to study Python, I copied a swarm intelligence library called acopy.

In acopy, many interesting Python grammars and idioms are used, and it is summarized that it is convenient among them.

This time, we'll look at a built-in function called vars.

What is vars?

There are several built-in functions in python, one of which is the function vars. vars (x) returns the __dic__ attribute of object $ x $ as a dictionary.

What is __dic__?

__dic__ is the dict attribute of a module or class instance object. The dict attribute contains the values associated with the names of all the properties set on the object.

Concrete example

Let's see in a simple code that vars returns the __dic__ attribute.

class A:

    def __init__(self, x, y):
        self.x = x
        self.y = y


def f():
    x = 50
    print(vars())


a = A(10, 20)
'''
{'x': 10, 'y': 20}
'''
print(vars(a))

'''
{'x': 50}
'''
f()

Try using vars on object a of class A. Then, you can get the __dic__ attribute set in the object a of class A, that is, all the instance information of a in the dictionary. Also, since the local symbol table in the function is defined in the function, if nothing is specified in vars, __dic__ of the local symbol table will be returned. Therefore, it returns a dictionary of x.

In this way, vars allows you to learn the __dic__ attribute.

Usage: Pass all objects

By using vars, for example, all information about an instance of a class can be passed to other class methods. This is because it can be combined with a function called ** Unpack **.

For example, take a look at the following code.

class KeywordPrinter:

    @staticmethod
    def printer(**kwargs):
        text_arr = [f'(key = {key}, value = {kwargs[key]})' for key in kwargs.keys()]
        return ', '.join(text_arr)


class A:

    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __repr__(self):
        return self.__class__.__name__ + KeywordPrinter.printer(**vars(self))


'''
A(key = x, value = 10), (key = y, value = 20)
'''
a = A(10, 20)
print(a)

First, define a class called KeywordPrinter that converts all dictionaries into strings.

In addition, we will define a method with the __repr__ attribute in class A so that print can output an arbitrary character string, aiming for a simpler debug state.

Now, in __repr__, I passed something called** vars (self)to KeywordPrinter. First, get the property dictionary information of instance a with vars (self). Then, by unpacking it and passing it to the Printer, the dictionary will be returned as a character string in an easy-to-read manner.

This is an extreme example and shouldn't be used much, but in actual coding, there are situations where you want to pass a local variable to another method, class, or function. At this time, you may be able to reduce the amount of coding by using ** vars (self).

I will study more.

References

-Difference between Python vars () and dir () -Get property information of Python class

Recommended Posts

[Road to intermediate level] Utilize Python's built-in function vars
[Road to Intermediate] What are Python's * args, ** kwargs?
[Road to Python Intermediate] Define __getattr__ function in class
A road to intermediate Python
[Road to Python Intermediate] Call a class instance like a function with __call__
Road to Linux Intermediate: Network Edition
[Road to Intermediate] Understanding Python Properties
[Road to intermediate Python] Use ternary operators
[Road to intermediate Python] Article link summary