我想要一个漂亮方便的属性做到以下几点:Python - 将属性设置为方法的值 - 最干净的方式?
from django.contrib.auth.models import User
user = User.objects.get(id=2)
user.company
<Company: Big Company L.L.C>
我目前解决这一使用lambda。在寻找答案时,看起来或许解决这个问题的“正确”方法是使用types.MethodType
,但我似乎无法解决这个问题。是的,我已经阅读Raymond excellent guide但我清楚地失去了一些东西。这里是我的那些有兴趣谁目前的解决方案..
# Defined Elsewhere
class User:
name = models.CharField(max_length=32)
class Company(models.Model):
users = models.ManyToManyField(User, related_name="companies", blank=True, null=True)
# Here is the meat of this..
class UserProfile(models.Model):
"""This defines Users"""
user = models.OneToOneField(User)
def get_company(self):
try:
companies = self.user.companies.all()[0]
except (AttributeError, IndexError):
return None
User.company = property(lambda u: UserProfile.objects.get_or_create(user=u)[0].get_company())
现在这个工程.. 但是,有没有更好的办法 - 我米不是疯狂的lambda?
是lambda导致任何问题?如果没有,你有一个你想要做的工作实施 - 为什么要让事情变得困难? – millimoose
不,它的工作,但我不完全适应他们。我一直用反模式的眼睛看着它们...... – rh0dium
在Python 2.x中要小心'AttributeError,IndexError:'。它只会捕获'AttributeError',并将捕获到的异常分配给'IndexError'。使用'except(AttributeError,IndexError):'代替。 –