Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to pass more than one argument to the property getter?

Consider the following example:

class A:     @property     def x(self): return 5 

So, of course calling the a = A(); a.x will return 5

But imagine that you want to be able to modify the property x.
This way, for example:

class A:     @property     def x(self, neg = False): return 5 if not neg else -5 

And call it with a = A(); a.x(neg=True)

That will raise a TypeError: 'int' object is not callable, that is quite normal, since our x is evaluated as 5.

So, I would like to know how one can pass more then one argument to the property getter, if it is possible at all.

like image 369
Rizo Avatar asked Apr 19 '11 11:04

Rizo


People also ask

Can a python property take arguments?

The property() method in Python provides an interface to instance attributes. It encapsulates instance attributes and provides a property, same as Java and C#. The property() method takes the get, set and delete methods as arguments and returns an object of the property class.

What is @property in Python class?

The @property Decorator In Python, property() is a built-in function that creates and returns a property object. The syntax of this function is: property(fget=None, fset=None, fdel=None, doc=None)

How do you pass an argument in Python?

The special syntax *args in function definitions in python is used to pass a variable number of arguments to a function. It is used to pass a non-key worded, variable-length argument list. The syntax is to use the symbol * to take in a variable number of arguments; by convention, it is often used with the word args.

Can you pass an object as an argument Python?

Python's language reference for assignment statements states that if the target is an object's attribute that supports assignment, then the object will be asked to perform the assignment on that attribute. If you pass the object as an argument to a function, then its attributes can be modified in place.


1 Answers

Note that you don't have to use property as a decorator. You can quite happily use it the old way and expose the individual methods in addition to the property:

class A:     def get_x(self, neg=False):         return -5 if neg else 5     x = property(get_x)  >>> a = A() >>> a.x 5 >>> a.get_x() 5 >>> a.get_x(True) -5 

This may or may not be a good idea depending on exactly what you're doing with it (but I'd expect to see an excellent justification in a comment if I came across this pattern in any code I was reviewing)

like image 83
ncoghlan Avatar answered Sep 28 '22 19:09

ncoghlan