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.
__type () behaves differently depending on the number of arguments. __
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.
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.
That's all about how to use type ()
, which I didn't know about.
There seems to be many surprising uses other than type ()
.
-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