【问题标题】:How to get the type of a class property (Django Model) in python如何在python中获取类属性(Django模型)的类型
【发布时间】:2017-12-21 13:48:20
【问题描述】:

我有一个具有不同属性的 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.'},
    )

如何检查 shortname 是 model.CharField 还是 model.Whatever?

【问题讨论】:

标签: python django


【解决方案1】:
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

【讨论】:

  • 他想检查类本身,而不是类的instance
  • 我也提到了类的例子。查看我已经更新的答案。
  • 另请注意,OP 正在询问 Django 模型类,与普通 Python 类相比,它在这方面的行为不同。请参阅docs.djangoproject.com/en/2.0/ref/models/meta/… 了解如何访问 Django 模型的字段。
  • pricetitle 是实例属性,这是他想要的。 Book 根本没有类属性。
  • 您可以将这些变量保留为实例变量或类变量,但仍然可以使用 type(..)isinstance 以相同的方式获取变量的类型(..) 函数。比如type(variable) 或者 isinstance(variable, Class)```。
【解决方案2】:

https://docs.djangoproject.com/en/2.0/ref/models/meta/#django.db.models.options.Options.get_field

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

【讨论】:

    猜你喜欢
    • 2015-04-12
    • 2019-09-28
    • 1970-01-01
    • 2018-03-19
    • 2017-07-21
    • 2018-02-16
    • 2020-01-29
    • 2019-07-27
    • 1970-01-01
    相关资源
    最近更新 更多