[Python] How to play with class variables with decorator and metaclass

When I want to write the handling process etc. concisely using a decorator, I use metaclass, but I always forget how to do it, so make a note

from types import MethodType, FunctionType, LambdaType

class MetaClass(type):
    def __new__(cls, name, bases, attr):
        def is_excutable(v):
            return isinstance(v, (MethodType, FunctionType, LambdaType))

        target = attr['target']

        for k, v in attr.items():
            if is_excutable(v) and getattr(v, '__flag', False):
                target.append((getattr(v, '__command'), v))

        klass = type.__new__(cls, name, bases, attr)
        klass.target = target
        return klass


def decorator(command=''):
    def decorate(func):
        setattr(func, '__flag', True)
        setattr(func, '__command', command)
        return func
    return decorate

class Klass(metaclass=MetaClass):
    target = []

    @decorator('command_name')
    def test_method(self):
        pass

print('Klass.target:', Klass.target)

Recommended Posts

[Python] How to play with class variables with decorator and metaclass
Fractal to make and play with Python
[REAPER] How to play with Reascript in Python
Trouble with Python pseudo-private variables and class inheritance
Python: Class and instance variables
Python class variables and instance variables
How to loop and play gif video with openCV
[How to!] Learn and play Super Mario with Tensorflow !!
How to write a Python class
Python: How to use async with
How to get started with Python
How to do Bulk Update with PyMySQL and notes [Python]
[Let's play with Python] Image processing to monochrome and dots
How to use FTP with Python
How to calculate date with python
How to write a metaclass that supports both python2 and python3
[Python] Inherit a class with class variables
How to log in to AtCoder with Python and submit automatically
How to import CSV and TSV files into SQLite with Python
How to make a surveillance camera (Security Camera) with Opencv and Python
How to use Serverless Framework & Python environment variables and manage stages
How to deal with errors when installing Python and pip with choco
I was addicted to confusing class variables and instance variables in Python
[ROS2] How to play a bag file with python format launch
How to use Python with Jw_cad (Part 2 Command explanation and operation)
How to build Python and Jupyter execution environment with VS Code
Create a Python function decorator with Class
How to package and distribute Python scripts
[Introduction to Python] How to use class in Python?
How to dynamically define variables in Python
How to install and use pandas_datareader [Python]
[Python] How to make a class iterable
How to work with BigQuery in Python
How to do portmanteau test with python
I want to play with aws with python
How to display python Japanese with lolipop
python: How to use locals () and globals ()
How to use __slots__ in Python class
How to enter Japanese with Python curses
[Python] How to calculate MAE and RMSE
How to use Python zip and enumerate
[Python] How to deal with module errors
How to use is and == in Python
How to install python3 with docker centos
Play with 2016-Python
[Introduction to Python] How to judge authenticity with if statement (True and None)
How to get the date and time difference in seconds with python
How to access data with object ['key'] for your own Python class
How to upload with Heroku, Flask, Python, Git (4)
How to read a CSV file with Python 2/3
Scraping tabelog with python and outputting to CSV
How to enjoy programming with Minecraft (Ruby, Python)
How to generate permutations in Python and C ++
Strategy on how to monetize with Python Java
How to create explanatory variables and objective functions
[python] Difference between variables and self. Variables in class
[Python] How to draw multiple graphs with Matplotlib
[Python] How to read excel file with pandas
How to crop an image with Python + OpenCV
[Python] How to read data from CIFAR-10 and CIFAR-100
How to convert SVG to PDF and PNG [Python]