如何获得Python中类属性(Django模型)的类型



我有一个具有不同属性的Python类,但我似乎找不到如何获得每个类型的类型。我想检查给定属性是否具有特定类型。

请注意,我在谈论课程而不是实例。

假设我有这个课:

class SvnProject(models.Model):
    '''
        SVN Projects model
    '''
    shortname = models.CharField(
        verbose_name='Repository name',
        help_text='An unique ID for the SVN repository.',
        max_length=256,
        primary_key=True,
        error_messages={'unique':'Repository with this name already exists.'},
    )

如何检查短名是模型。

class Book:
    i = 0 # test class variable
    def __init__(self, title, price):
        self.title = title
        self.price = price
    ...
# let's check class variable type
# we can directly access Class variable by
# ClassName.class_variable with or without creating an object
print(isinstance(Book.i, int))
# it will print True as class variable **i** is an **integer**
book = Book('a', 1)
# class variable on an instance
print(isinstance(book.i, int))
# it will print True as class variable **i** is an **integer**
print(isinstance(book.price, float))
# it print False because price is integer
print(type(book.price))
# <type 'int'>
print(isinstance(book, Book))
# it will print True as book is an instance of class **Book**

对于 django 相关项目,就像

from django.contrib.auth.models import User
from django.db.models.fields import AutoField
print(isinstance(User._meta.get_field('id'), AutoField))
# it will print True

请参阅https://docs.djangoproject.com/en/en/2.0/ref/models/meta/meta/#django.db.models.options.options.options.get_get_field

>>> SvnProject._meta.get_field('shortname')
<django.db.models.fields.CharField: shortname>

最新更新