[Python] How to use two types of type ()

Introduction

When I'm reading the code around Django's Manager at work I found an unfamiliar usage of type ().

Click here for the GitHub link (https://github.com/django/django/blob/master/django/db/models/manager.py#L100-L108)


@classmethod
def from_queryset(cls, queryset_class, class_name=None):
    if class_name is None:
        class_name = '%sFrom%s' % (cls.__name__, queryset_class.__name__)
    return type(class_name, (cls,), {
        '_queryset_class': queryset_class,
        **cls._get_queryset_methods(queryset_class),
    })

Three arguments are passed to type ... ??? what's this?

When I looked it up, it was properly written in the Documentation of the Python standard library. (That's right)

It's almost like a quote, but I'll briefly summarize it.

Conclusion

__type () behaves differently depending on the number of arguments. __


1. (Probably) common usage

If there is only one argument, returns the type of object. The return value is a type object, which is typically the same object returned by object.__ class__. (Quoted from Python documentation)


>>> class Bar:
...     pass

>>> class Foo(Bar):
...     pass

Prepare a class Bar and a class Foo that inherits it.

At this time, the behavior of type () is as follows.

>>> foo = Foo()
>>> type(foo)
<class '__main__.Foo'>

>>> type(foo) is Foo
True

>>> type(foo) is Bar
False

In some cases, use it properly with ʻis instance ()`.

That was a story I knew.

2. How to use it

class type(name, bases, dict)

If there are three arguments, it returns a new type object. It's essentially a dynamic form of class statement. (Quoted from Python documentation)

The documentation states that the following two statements create the same type object.


>>> class X:
...     a = 1

>>> X = type('X', (object,), dict(a=1))

First argument: Name of class to generate Second argument: Inheriting class Third argument: Object attributes

It has become.

I will actually try it.


>>> class Bar:
...     a=1
...
...     def print_hogefuga(self):
...         print('hogefuga')
...

>>> Foo = type('Foo', (Bar,), dict(b=2))

>>> foo = Foo()
>>> foo.print_hogefuga()
hogefuga
>>> foo.a
1
>>> foo.b
2

In this way, we were able to create a FooClass that inherits from BarClass.

Summary

That's all about how to use type (), which I didn't know about.

There seems to be many surprising uses other than type ().

Reference / citation

-Type function, isinstance function to get / judge type in Python --It explains the commonly used type () and ʻis instance ()`. --Python built-in function documentation / # type ――It was interesting because there were many things I had never used. It's a good opportunity, so I'll review it.

Recommended Posts

[Python] How to use two types of type ()
[Python] Summary of how to use pandas
[Python2.7] Summary of how to use unittest
Summary of how to use Python list
[Python2.7] Summary of how to use subprocess
[Question] How to use plot_surface of python
Summary of how to use MNIST in Python
How to get dictionary type elements of Python 2.7
python3: How to use bottle (2)
[Python] How to use list 1
How to use Python argparse
Python: How to use pydub
[Python] How to use checkio
[Python] How to use input ()
How to use Python lambda
[Python] How to use virtualenv
python3: How to use bottle (3)
python3: How to use bottle
How to use Python bytes
I tried to summarize how to use matplotlib of python
How to write a list / dictionary type of Python3
How to use Python Kivy ① ~ Basics of Kv Language ~
Summary of how to use pandas.DataFrame.loc
[Python] How to use Pandas Series
How to use Requests (Python Library)
How to use SQLite in Python
Summary of how to use pyenv-virtualenv
[Python] How to use list 3 Added
How to use Mysql in python
How to use OpenPose's Python API
How to use ChemSpider in Python
How to use FTP with Python
Python: How to use pydub (playback)
How to use PubChem in Python
How to use python zip function
Summary of how to use csvkit
[Python] How to use Typetalk API
[Python] Summary of how to use split and join functions
Comparison of how to use higher-order functions in Python 2 and 3
[Introduction to Python] How to use class in Python?
How to install and use pandas_datareader [Python]
[python] How to use __command__, function explanation
How to calculate Use% of df command
[Python] How to use import sys sys.argv
[Python] Organizing how to use for statements
Memorandum on how to use gremlin python
python: How to use locals () and globals ()
How to use __slots__ in Python class
Jupyter Notebook Basics of how to use
How to use "deque" for Python data
Basics of PyTorch (1) -How to use Tensor-
How to use Python zip and enumerate
[Python] Understand how to use recursive functions
How to use regular expressions in Python
How to use is and == in Python
[Blender x Python] How to use modifiers
How to use Python Kivy (reference) -I translated Kivy Language of API reference-
Basic grammar of Python3 system (how to use functions, closures, lambda functions)
How to use xml.etree.ElementTree
How to use Python-shell
How to use the C library in Python