如何定义类定义的 Python 属性 *outside*? [英] How do I define a Python property *outside* of a class definition?
本文介绍了如何定义类定义的 Python 属性 *outside*?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在类定义的外部定义一个 Python 属性:
I would like to define a Python property outside of a class definition:
c = C()
c.user = property(lambda self: User.objects.get(self.user_id))
print c.user.email
但我收到以下错误:
AttributeError: 'property' object has no attribute 'email'
在类定义之外定义属性的正确语法是什么?
What is the correct syntax for defining a property outside of a class definition?
顺便说一句:我正在使用 生菜
Btw: I'm using 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()
推荐答案
像 c
这样的对象实例不能有属性;只有像 C
这样的类可以有属性.所以需要在类上设置属性,而不是实例,因为Python只在类上查找:
Object instances like c
cannot have properties; only classes like C
can have properties. So you need to set the property on the class, not the instance, because Python only looks for it on the class:
C.user = property(lambda self: User.objects.get(self.user_id))
这篇关于如何定义类定义的 Python 属性 *outside*?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文