【问题标题】:Unexpected behavior of static variables in python [duplicate]python中静态变量的意外行为[重复]
【发布时间】:2016-01-07 17:48:12
【问题描述】:

我正在学习django,这是我创建的模型

class UserProfile(models.Model):
    name = models.CharField(max_length=50, verbose_name="Name")
    login = models.CharField(max_length=25, verbose_name="Login")
    password = models.CharField(max_length=100, verbose_name="Password")
    phone = models.CharField(max_length=20, verbose_name="Phone number")

    def __str__ (self):
        return self.name

由于name是静态变量,所以在方法__str__中也可以这样调用

    def __str__ (self):
        return UserProfile.name

但是当我尝试使用上述方法访问变量时,我得到以下错误

AttributeError at /admin/TasksManager/userprofile/
type object 'UserProfile' has no attribute 'name'
Request Method: GET
Request URL:    http://127.0.0.1:8000/admin/TasksManager/userprofile/
Django Version: 1.6
Exception Type: AttributeError
Exception Value:    
type object 'UserProfile' has no attribute 'name'
Exception Location: C:\Users\X\django_book\Work_manager\TasksManager\models.py in __str__, line 18
Python Executable:  C:\Users\X\django_book\Scripts\python.EXE
Python Version: 3.4.3
Python Path:    
['C:\\Users\\X\\django_book\\Work_manager',
 'C:\\Windows\\system32\\python34.zip',
 'C:\\Users\\X\\django_book\\DLLs',
 'C:\\Users\\X\\django_book\\lib',
 'C:\\Users\\X\\django_book\\Scripts',
 'C:\\Python34\\Lib',
 'C:\\Python34\\DLLs',
 'C:\\Users\\X\\django_book',
 'C:\\Users\\X\\django_book\\lib\\site-packages']
Server time:    Thu, 7 Jan 2016 23:10:34 +0530

为什么会这样??

我在下面的课程中应用了相同的技术,效果很好

class Rect:

    status = "this is test"

    def __init__(self, l, b):
        self.l = l
        self.b = b

    def something(self):
        return Rect.status

为什么会有矛盾?

【问题讨论】:

    标签: python django python-2.7 python-3.x static-members


    【解决方案1】:

    Django 模型不包含静态变量。元类使用它们来定义实际的实例变量。你不能通过类访问它们。

    【讨论】:

    • 那么我怎样才能在 Rect 类中实现同样的目标呢?
    • 在 Django 中,有很多元类技巧使这成为可能;这不是你可以启用的。
    • 我不太明白你想要达到什么目的。
    • 仅用于学习目的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-23
    • 1970-01-01
    • 2015-08-11
    • 2020-02-16
    • 2014-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多