khajvah
khajvah

Reputation: 5090

Are class names objects in python?

I am learning python and I started reading about Django framework. In examples, here is what I found:

class Person(models.Model):
    name = models.CharField(max_length=128)

    def __str__(self):              # __unicode__ on Python 2
        return self.name

class Group(models.Model):
    name = models.CharField(max_length=128)
    members = models.ManyToManyField(Person, through='Membership')

    def __str__(self):              # __unicode__ on Python 2
        return self.name

It is not important what the code does. My question is about function ManyToManyField(Person, through='Membership'). There we are passing a class name to a function.

Why is it allowed? Are class NAMES objects in python?

Upvotes: 0

Views: 91

Answers (1)

Tanveer Alam
Tanveer Alam

Reputation: 5275

Yes classes are objects in Python. Every entity in python inherits from the base entity object and class also inherits from object.

>>> class People:
...     pass
... 
>>> type(People)
<type 'classobj'>
>>> 
>>> isinstance(People, object)
True

This is similar as:

>>> class Group(object):
...     pass
... 
>>> type(Group)
<type 'type'>
>>> isinstance(Group, object)
True

In Python 3 both class class_name: and class class_name(object): returns same type:

In [1]: class Person:
   ...:     pass
   ...: 
In [2]: Person
Out[2]: __main__.Person
In [3]: class Group(object):
   ...:     pass
   ...: 
In [4]: Group
Out[4]: __main__.Group

Every thing in Python is an object

>>> my_list = []
>>> my_list
[]
>>> isinstance(my_list, object)
True

Upvotes: 3

Related Questions