+ 2
Can someone explain me the property decorator in python.??
2 ответов
+ 2
The property decorator is an inbuilt one which allows you to get a value of an attribute. More specifically used for private attributes (starting with either one of or two underscores "_") I.e.
class Foo():
self._value = "hello"
@property
def value():
return self._value
x = Foo()
print(x.value)
this should output:
hello
you can combine this with the setattr decorator to also set the value.
add in to the above class
@value.setattr
def value (newvalue):
self._value = newvalue
then in our class instance we can:
x.value = "hello world"
print (x.value)
this will now print:
hello world
this might seem silly in the example but it's a a nicer than writing your own get and set functions for values. a useful expansion might be that you want to make sure the type is correct. I.e a string, if so our setattr becomes:
@value.setattr
def value (newvalue):
if isinstance(newvalue, str):
self._value = newvalue
else:
raise AttributeError("I only except strings")
so now if you try
x.value = 16
The compiler will throw an attribute error
I may have gotten the names wrong above but hopefully they are correct. not in front of a PC to test.
+ 2
Here is an example of what a decorator may be useful for:
https://code.sololearn.com/cD09ijlIS6Ev/?ref=app