How to create a property with its name in a string?

Using Python I want to create a property in a class, but having its name in a string. Usually you do:

blah = property(get_blah, set_blah, del_blah, "bleh blih")

where get_, set_, and del_blah are defined respectively. I tried to do the same with the property name in a variable, like this:

setattr(self, "blah", property(self.get_blah, self.set_blah, self.del_blah, "bleh blih"))

But that does not work. The first case blah returns the value of the property, in the second case it returns the property, that is <property object at 0xbb1aa0>. How can I define it so that it works?

+3
source share
3 answers

As far as I would say, the difference is that in the first version you change the attribute of the blah class to the result of the property, and in the second you set it in the instance (which is different!).

How about this version:

setattr(MyClass, "blah", property(self.get_blah, self.set_blah,
        self.del_blah, "bleh blih"))

:

setattr(type(self), "blah", property(self.get_blah, self.set_blah,
        self.del_blah, "bleh blih"))
+2

- 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

a_value
b_value
c_value
+1

, , , getattr setattr.

:

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

It will be printed:

You're getting foo
You're getting bar

That way you can have a common getter and setter that has a property name in a string and does something with it.

+1
source

Source: https://habr.com/ru/post/1714059/


All Articles