Reputation: 287520
Using Python I want to create a property in a class, but having the name of it in a string. Normally you do:
blah = property(get_blah, set_blah, del_blah, "bleh blih")
where get_, set_ and del_blah have been defined accordingly. I've tried to do the same with the name of the property in a variable, like this:
setattr(self, "blah", property(self.get_blah, self.set_blah, self.del_blah, "bleh blih"))
But that doesn't work. The first case blah returns the value of the property, on the second case, it returns a property, that is <property object at 0xbb1aa0>
. How should I define it so it works?
Upvotes: 3
Views: 405
Reputation: 12728
As much I would say, the difference is, that in the first version, you change the classes attribute blah to the result of property and in the second you set it at the instance (which is different!).
How about this version:
setattr(MyClass, "blah", property(self.get_blah, self.set_blah,
self.del_blah, "bleh blih"))
you can also do this:
setattr(type(self), "blah", property(self.get_blah, self.set_blah,
self.del_blah, "bleh blih"))
Upvotes: 2
Reputation: 15493
If I understand what you're trying to do, you could accomplish it by overriding the class's getattr and setattr methods.
For example:
class Something(object):
def __getattr__(self, name):
# The name of the property retrieved is a string called name
return "You're getting %s" % name
something = Something()
print something.foo
print something.bar
Will print:
You're getting foo
You're getting bar
This way you can have a generic getter and setter that has the name of the property in a string and does something with it accordingly.
Upvotes: 1
Reputation: 127467
One way is to write into locals():
class X:
for attr in ["a","b","c"]:
def getter(self, name=attr):
return name+"_value"
locals()[attr] = property(getter, None, None, attr)
x = X()
print x.a
print x.b
print x.c
gives
a_value
b_value
c_value
Upvotes: 1