【问题标题】:How do I define a Python property *outside* of a class definition?如何在类定义之外定义 Python 属性?
【发布时间】:2011-12-18 10:05:32
【问题描述】:

我想在类定义外部定义一个Python属性:

c = C()
c.user = property(lambda self: User.objects.get(self.user_id))
print c.user.email

但我收到以下错误:

AttributeError: 'property' object has no attribute 'email'

在类定义之外定义属性的正确语法是什么?

顺便说一句:我正在使用lettuce

from lettuce import *
from django.test.client import Client
Client.user_id = property(lambda self: self.browser.session.get('_auth_user_id'))
Client.user = property(lambda self: User.objects.get(self.user_id))

@before.each_scenario 
def set_browser(scenario):
    world.browser = Client()

【问题讨论】:

    标签: python properties


    【解决方案1】:

    c 这样的对象实例不能有属性;只有像C 这样的类才能有属性。所以你需要在类上设置属性,而不是在实例上,因为 Python 只在类上寻找它:

    C.user = property(lambda self: User.objects.get(self.user_id))
    

    【讨论】:

    • 嗯,我试过了,但我得到了这个错误:AttributeError: 'thread._local' object has no attribute 'user'
    • 如果你得到 that 错误,那么这意味着这个问题的移动部分比你愿意在你的问题中承认的要多。 :) 请向我们展示您的实际代码以及您正在使用的 import 语句和库。作为回报,我们将向您展示为什么会出现线程本地错误!
    • 您是否在以Client.user = 开头的行上收到该错误?我什至在他们的源代码中都看不到 Django or Celery 使用线程局部变量的地方,而且我无法重现您的问题(如果我将您提供的脚本放在 @987654326 中,它不会独立运行@文件)。
    猜你喜欢
    • 1970-01-01
    • 2022-11-12
    • 1970-01-01
    • 2015-09-08
    • 2018-06-12
    • 1970-01-01
    • 2013-10-17
    • 2020-02-13
    • 2012-03-16
    相关资源
    最近更新 更多