How can I use descriptors for non-static methods?

2024/10/13 20:16:41

I am aware that I can use descriptors to change static property as if it were a normal property. However, when I try using descriptors for a normal class property, I end up changing the object it references to, instead of the value in the object.

If I have

Normal use, considering that the method(param) returns an object

class SomeClass():property = method(param)

I can then do:

instance = SomeClass()
instance.property = 3

and be able to have that setting handled by the the class of which property is an instance.

Now, if I instead have

class SomeClass():def__init__(self):self.property = method(param)

and I do:

instance = SomeClass()
instance.property = 3

That code does not work, and I overwrite the reference to the object created by method(param) with 3, instead of having that setting handled by the descriptor.

Is there a way I can use descriptors without static methods? In essence, I need to be able to create several instances of the class, each with its own unique properties that can be altered using the convenient descriptor method. Is that possible?

Python version: 2.7

Thanks!

Answer

Descriptors provide a simple mechanism for variations on the usual patterns of binding functions into methods.

To recap, functions have a __get__() method so that they can be converted to a method when accessed as attributes. The non-data descriptor transforms an obj.f(*args) call into f(obj, *args). Calling klass.f(*args) becomes f(*args).

This chart summarizes the binding and its two most useful variants:

Transformation  Called from an Object   Called from a Class
function            f(obj, *args)           f(*args)
staticmethod        f(*args)                f(*args)
classmethod         f(type(obj), *args)     f(klass, *args)

Static methods return the underlying function without changes. Calling either c.f or C.f is the equivalent of a direct lookup into

object.__getattribute__(c, "f") or object.__getattribute__(C, "f").As a result, the function becomes identically accessible from either an object or a class.

Good candidates for static methods are methods that do not reference the self variable.

class RevealAccess(object):"""A data descriptor that sets and returns valuesnormally and prints a message logging their access."""def __init__(self, initval=None, name='var'):self.val = initvalself.name = namedef __get__(self, obj, objtype):print 'Retrieving', self.namereturn self.valdef __set__(self, obj, val):print 'Updating', self.nameself.val = val>>> class MyClass(object):
...     x = RevealAccess(10, 'var "x"')
...     y = 5
...
>>> m = MyClass()
>>> m.x
Retrieving var "x"
10
>>> m.x = 20
Updating var "x"
>>> m.x
Retrieving var "x"
20
>>> m.y
5
https://en.xdnf.cn/q/118038.html

Related Q&A

psycopg2 not all arguments converted during string formatting

I am trying to use psycopg2 to insert a row into a table from a python list, but having trouble with the string formatting.The table has 4 columns of types (1043-varchar, 1114-timestamp, 1043-varchar, …

inherited function odoo python

i want to inherit function in module hr_holidays that calculate remaining leaves the function is :hr_holiday.py:def _get_remaining_days(self, cr, uid, ids, name, args, context=None):cr.execute("&…

ValueError in pipeline - featureHasher not working?

I think Im having issues getting my vectorizer working within a gridsearch pipeline:data as panda df x_train:bathrooms bedrooms price building_id manager_id 10 1.5 3 3000 53a5b119b…

pandas dataframe: meaning of .index

I am trying to understand the meaning of the output of the following code:import pandas as pdindex = [index1,index2,index3] columns = [col1,col2,col3] df = pd.DataFrame([[1,2,3],[1,2,3],[1,2,3]], index…

Extract text inside XML tags with in Python (while avoiding p tags)

Im working with the NYT corpus in Python and attempting to extract only whats located inside "full_text" class of every .xml article file. For example: <body.content><block class=&qu…

Python (Flask) and MQTT listening

Im currently trying to get my Python (Flask) webserver to display what my MQTT script is doing. The MQTT script, In essence, its subscribed to a topic and I would really like to categorize the info it …

I dont show the image in Tkinter

The image doesnt show in Tkinter. The same code work in a new window, but in my class it does not. What could be the problem ?import Tkinterroot = Tkinter.Tkclass InterfaceApp(root):def __init__(self,…

Read temperature with MAX31855 Thermocouple Sensor on Windows IoT

I am working on a Raspberry Pi 2 with Windows IoT. I want to connect the Raspberry Pi with a MAX31855 Thermocouple Sensor which I bought on Adafruit. Theres a Python libary available on GitHub to read …

PIP: How to Cascade Requirements Files and Use Private Indexes? [duplicate]

This question already has an answer here:Installing Packages from Multiple Servers from One or More Requirements File(1 answer)Closed 9 years ago.I am trying to deploy a Django app to Heroku where one …

Python error: TypeError: cannot compare a dtyped [float64] array with a scalar of type [bool]

Below is a small sample of my dataframe. In [10]: dfOut[10]:TXN_KEY Send_Agent Pay_Agent Send_Amount Pay_Amount 0 13272184 AWD120279 AEU002152 85.99 85.04 1 13272947 ARA03012…