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
But I get the following error:
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()
Python isn't like Java or C# and you can just have functions that aren't part of any class. If you want to group together functions you can just put them together in the same module, and you can nest modules inside packages. Only use classes when you need to create a new data type, not just to group functions together.
Thus, the variables can be defined inside the class, outside the class, and inside the methods in Python. The variables defined outside the class can be accessed by any method or class by just writing the variable name. So, in this article, we are going to learn how to define a method outside of the class definition.
In Python, a property in the class can be defined using the property() function. The property() method in Python provides an interface to instance attributes. It encapsulates instance attributes and provides a property, same as Java and C#.
Python property() function returns the object of the property class and it is used to create property of a class. Parameters: fget() – used to get the value of attribute. fset() – used to set the value of attribute.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With