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.
@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.
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.
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.
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.
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With