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

前端 未结 1 1150
北海茫月
北海茫月 2021-02-19 16:17

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.u         


        
相关标签:
1条回答
  • 2021-02-19 17:19

    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))
    
    0 讨论(0)
提交回复
热议问题