如何在类定义的*之外定义Python属性?

Jos*_*ian 13 python properties

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

c = C()
c.user = property(lambda self: User.objects.get(self.user_id))
print c.user.email
Run Code Online (Sandbox Code Playgroud)

但是我收到以下错误:

AttributeError: 'property' object has no attribute 'email'
Run Code Online (Sandbox Code Playgroud)

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

编辑:我正在使用生菜

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()
Run Code Online (Sandbox Code Playgroud)

Bra*_*des 13

对象实例就像c没有属性一样; 只有类C可以拥有属性.所以你需要在类而不是实例上设置属性,因为Python只在类上查找它:

C.user = property(lambda self: User.objects.get(self.user_id))
Run Code Online (Sandbox Code Playgroud)