QxQ
QxQ

Reputation: 675

how do you return a property and save it as a global variable? (python)

here is my code:

def createProp(fget, fset, fdel):

    class prop(object):
        get=property(fget,fset,fdel)

    return prop().get
x=createProp(getter,setter,deleter)

what I would like to do is have it return a property, so that I can make the variable x a property, but I can't figure out how to make a function like this. what it is doing instead is returning the value of the property, not the property itself.

python 2.6

Upvotes: 0

Views: 225

Answers (1)

user395760
user395760

Reputation:

createProp = property

Properties are perfectly ordinary objects. property is just another class. You can create an instance of it at runtime, in whatever context you want (no need for a class), pass them around, etc. And yes, you could (pointlessly) create one in a local class and then fetch it from there. But as the whole point of properties is overriding attribute access on instance, you'd have to fetch it from the class: return prop.get.

However, as property works its magic by means of the descriptor protocol, and descriptors have to be in a class to work. You can't have a global (or local) variable that's a property -- well, you can, but using it would just give you the descriptor object, not run fget, and assignment wouldn't trigger fset. You cannot do anything like that, and you shouldn't.

Upvotes: 4

Related Questions