How to create an instance of a particular class from dict using __new__ () in python

Sometimes you can use __new__ () in python to instantiate a particular class from a dict. It may be convenient once in a while. How to create an instance by bypassing the defined __init__ ().

How to create a normal instance

It is assumed that the following classes are defined.

class Person(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        return "{self.__class__.__name__}({self.name}, {self.age})".format(self=self)

Normally, it is initialized by passing a value as a direct argument as shown below.

p = Person("foo", 20)
print(p)
# Person(foo, 20)

Conversion from dict

If you want to create an instance from dict, you can write it like this.

d = {"name": "foo", "age": 20}
p = Person.__new__(Person)
p.__dict__.update(d)
print(p)
Person(foo, 20)

Isn't Person (** d) enough?

In the case like the previous example, Person (** d) can also be used to create an instance using dict data. Is this enough?

Sometimes that's not the case. For example, when creating test data, you may want to directly initialize with the calculated value. In a situation where init () is defined with various disturbing calculations in such a class, and you want to bypass the calculation and specify a direct value to initialize the instance.

class X(object):
    def __init__(self, d):
        self.y = foo(d)
        self.z = boo(d)

Details

__new__ () is used to create an object when the class is used as a callable object.

  1. Create an object with __new__ ()
  2. Initialize the object with __init __ ()

Also, the instance variable itself of the object is stored in self.__dict__. Therefore, it is possible to only create an object with __new__ () and update __dict__ later.

Caution

Of course, note that __init __ () is not called.

class X(object):
    def __init__(self, d):
        self.x = foo(d)
        self.y = boo(d)
        raise RuntimeError("hmm")


x = X.__new__(X)
x.__dict__.update({"y": 10, "z": 20})
print(x, x.y, x.z)
# <__main__.X object at 0x10f7e4f28> 10 20

Recommended Posts

How to create an instance of a particular class from dict using __new__ () in python
Create an instance of a predefined class from a string in Python
How to create a heatmap with an arbitrary domain in Python
Various ways to create an array of numbers from 1 to 10 in Python.
How to create a JSON file in Python
How to generate a new loggroup in CloudWatch using python within Lambda
How to get a value from a parameter store in lambda (using python)
[Python] [Word] [python-docx] Try to create a template of a word sentence in Python using python-docx
[Python] How to sort dict in list and instance in list
How to create an image uploader in Bottle (Python)
How to execute a command using subprocess in Python
How to create a kubernetes pod from python code
[GCF + Python] How to upload Excel to GCS and create a new table in BigQuery
How to create a radial profile from astronomical images (Chandra, XMM etc.) using python
How to use NUITKA-Utilities hinted-compilation to easily create an executable file from a Python script
Don't take an instance of a Python exception class directly as an argument to the exception class!
How to slice a block multiple array from a multiple array in Python
How to use the __call__ method in a Python class
How to develop in a virtual environment of Python [Memo]
How to get a list of built-in exceptions in python
How to write a Python class
A memo to generate a dynamic variable of class from dictionary data (dict) that has only standard type data in Python3
How to quickly count the frequency of appearance of characters from a character string in Python?
[Python] How to create a table from list (basic operation of table creation / change of matrix name)
How to determine the existence of a selenium element in Python
How to know the internal structure of an object in Python
How to make a string into an array or an array into a string in Python
How to check the memory size of a variable in Python
How to get a string from a command line argument in python
How to check the memory size of a dictionary in Python
How to create a large amount of test data in MySQL? ??
How to create a clone from Github
[Introduction to Python] How to use class in Python?
[Python] How to make a class iterable
How to get a stacktrace in python
How to use __slots__ in Python class
Generate a class from a string in Python
How to create a repository from media
How to send a visualization image of data created in Python to Typetalk
Create a tool to automatically furigana with html using Mecab from Python3
[Python] How to put any number of standard inputs in a list
I want to color a part of an Excel string in Python
How to format a list of dictionaries (or instances) well in Python
"Cython" tutorial to make Python explosive: How to parse an Enum class defined in C ++ code into a Python Enum.
Edit Excel from Python to create a PivotTable
Create a GIF file using Pillow in Python
How to open a web browser from python
How to clear tuples in a list (Python)
How to create a function object from a string
Summary of how to import files in Python 3
I want to create a window in Python
Create a New Todoist Task from Python Script
How to generate a Python object from JSON
Summary of how to use MNIST in Python
How to notify a Discord channel in Python
Create a new page in confluence with Python
Create a datetime object from a string in Python (Python 3.3)
[Python] How to draw a histogram in Matplotlib
How to create a Rest Api in Django
Create a MIDI file in Python using pretty_midi
How to pass the execution result of a shell command in a list in Python