Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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()
like image 291
Joseph Turian Avatar asked Oct 30 '11 23:10

Joseph Turian


People also ask

How do you define a function outside the class in Python?

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.

Can methods be defined outside of a class?

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.

How do you define a class property in Python?

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

How do you set a property of an object Python?

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.


1 Answers

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))
like image 135
Brandon Rhodes Avatar answered Oct 08 '22 22:10

Brandon Rhodes