如何在类定义外部定义Python属性?

16 投票
1 回答
4427 浏览
提问于 2025-04-17 05:18

我想在一个类的定义之外定义一个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()

1 个回答

19

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

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

撰写回答