Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if class property has a setter

I need to list all the attribute of a class that are properties and have a setter. For example with this class:

class MyClass(object):
    def __init__(self):
        self. a = 1
        self._b = 2
        self._c = 3

    @property
    def b(self):
        return self._b

    @property
    def c(self):
        return self._c

    @c.setter
    def c(self, value):
        self._c = value

I need to get the attribute c but not a and b. Using this answers: https://stackoverflow.com/a/5876258/7529716 i can get the property object b and c.

But is their a way to know if those properties have a setter other than trying:

inst = MyClass()    
try:
    prev = inst.b
    inst.b = None
except AttributeError:
    pass # No setter
finally:
    inst.b = prev  

Thanks in advance.

like image 485
Yassine Faris Avatar asked Apr 20 '18 13:04

Yassine Faris


People also ask

Is @property a getter?

@property is used to get the value of a private attribute without using any getter methods. We have to put a line @property in front of the method where we return the private variable. To set the value of the private variable, we use @method_name.

Are getters and setters properties?

Accessor properties are represented by “getter” and “setter” methods. In an object literal they are denoted by get and set : let obj = { get propName() { // getter, the code executed on getting obj. propName }, set propName(value) { // setter, the code executed on setting obj.

What is a setter in OOP?

Getters and setters are used to protect your data, particularly when creating classes. For each instance variable, a getter method returns its value while a setter method sets or updates its value. Given this, getters and setters are also known as accessors and mutators, respectively.

What is setter in js?

In JavaScript, a setter can be used to execute a function whenever a specified property is attempted to be changed. Setters are most often used in conjunction with getters to create a type of pseudo-property. It is not possible to simultaneously have a setter on a property that holds an actual value.


1 Answers

property objects store their getter, setter and deleter in the fget, fset and fdel attributes, respectively. If a property doesn't have a setter or deleter, the attribute is set to None.

This means you can simply filter out those properties whose fset attribute is set to None:

def get_writeable_properties(cls):
    return [attr for attr, value in vars(cls).items()
                 if isinstance(value, property) and value.fset is not None]
>>> get_writeable_properties(MyClass)
['c']
like image 84
Aran-Fey Avatar answered Oct 12 '22 09:10

Aran-Fey