繁体   English   中英

如何定义类定义的 Python 属性 *outside*?

[英]How do I define a Python property *outside* of a class definition?

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

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

顺便说一句:我在用生菜

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()

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM