是python中的类名对象吗?

时间:2015-01-15 09:59:26

标签: python django class

我正在学习python,我开始阅读有关Django框架的内容。在示例中,这是我发现的:

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

代码的作用并不重要。我的问题是关于函数ManyToManyField(Person, through='Membership')。我们将类名传递给函数。

为什么允许?是python中的类NAMES对象吗?

1 个答案:

答案 0 :(得分:3)

classes是Python中的对象。 python中的每个实体都继承自基础实体object,而class也继承自object

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

这类似于:

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

Python 3 中,class class_name:class class_name(object):都返回相同的类型:

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

Python中的每件事都是object

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