operation on a variable inside a class in python

2024/10/6 0:29:06

I'm new with oop and python. I've been trying to do a simple thing: there is class called Foo(),it contains a variable called x which is initially set to zero.

>>>a = Foo()
>>>a.x
>>>0 

now I want to give a new value to x so:

>>>p.x = 1983

now a math operation should happen to x, for instance 1 is add to x.now x is 1984,so now when I call x:

>>> p.x
>>> 1984

also the program should check that whether or not the value given to x is negative or not.If it is negative it should return -1. I did this but it didn't work:(as I said it should do some mathematical operation on x,the operation itself is not really important)

class Foo():x = 0if x > 0:x %= 100elif x < 0:x = -1

I really don't now how should I update a class variable in they I mentioned. Thank you very much for your attention.

Answer

Assuming you don't need actual class attributes (you're always constructing an instance of Foo to use the attribute anyway, and it's not common for class attributes to be both public and logically mutable), the correct solution is to make x a property that wraps an instance attribute, which has independent values per instance, established in the __init__ initializer for the class:

class Foo:def __init__(self):self._x = 0  # _x is a protected instance attr that the property uses behind the scenes@propertydef x(self):  # getter for x is normalreturn self._x@x.setterdef x(self, newx):  # setter for x massages the value before setting itif newx >= 0:  # Cheaper to handle 0 on same code path as > 0 so you needn't test < 0newx %= 100else:newx = -1self._x = newx

Usage is pretty simple:

>>> myfoo = Foo()
>>> myfoo.x = 1983
>>> myfoo.x
83
>>> myfoo.x = -3748972983
>>> myfoo.x
-1

In case it really needs to be a class attribute and it must be accessible on instances, the solution gets ugly, as you need a metaclass to provide propertys on classes, and additional properties on the class itself to delegate access on instances to the class itself.

Note: I strongly discourage actually doing this as anything other than an exercise:

class FooMeta(type):  # Inheriting from type makes metaclass@propertydef x(cls):return cls._x@x.setterdef x(cls, newx):if newx >= 0:newx %= 100else:newx = -1cls._x = newxclass Foo(metaclass=FooMeta):_x = 0# Must make properties on class if instances are to "benefit" from class property@propertydef x(self):return type(self).x@x.setterdef x(self, newx):type(self).x = newx

That allows the following to work:

>>> Foo.x  # x exists on Foo itself, not just instances
>>> Foo.x = 1983
>>> Foo.x
83
>>> f = Foo()
>>> f.x  # Accessible on instances too
83
>>> f.x = -234789
>>> f.x  # Same behavior on instance
-1
>>> Foo.x  # Changing instance changed class
https://en.xdnf.cn/q/119003.html

Related Q&A

Print several sentences with different colors

Im trying to print several sentences with different colors, but it wont work, I only got 2 colors, the normal blue and this redimport sys from colorama import init, AnsiToWin32stream = AnsiToWin32(sys.…

Discord bot to send a random image from the chosen file

I am making a discord bot that randomly chooses an image (images) which is in the same directory (Cats) as the python file(cats.py). This is what my code looks like right now: Cats = os.path.join(os.pa…

pytest - patched method of a class does not return the mock value

My code is fairly simple but i dont understand what is going on :class MyDb :def some_func( arg ) :....while my test code is :@mock.patch(mypkg.mydb) @pytest.mark.parametrize( func_dummy_value ) :( [ {…

New instance of toplevel classes make overlapping widgets

Im generally new to python and tkinter. Ive been programming maybe about a year or so, and Ive just started to try to make each tkinter toplevel window its own class because Ive heard that its the righ…

Regex End of Line and Specific Chracters

So Im writing a Python program that reads lines of serial data, and compares them to a dictionary of line codes to figure out which specific lines are being transmitted. I am attempting to use a Regul…

Is it possible to scrape webpage without using third-party libraries in python?

I am trying to understand how beautiful soup works in python. I used beautiful soup,lxml in my past but now trying to implement one script which can read data from given webpage without any third-party…

Different model performance evaluations by statsmodels and scikit-learn

I am trying to fit a multivariable linear regression on a dataset to find out how well the model explains the data. My predictors have 120 dimensions and I have 177 samples:X.shape=(177,120), y.shape=(…

Python to search CSV file and return relevant info

I have a csv file with information about some computers on our network. Id like to be able to type from the command line a quick line to bring me back the relevant items from the csv. In the format:$…

Remove all elements matching a predicate from a list in-place

How can I remove all elements matching a predicate from a list IN-PLACE? T = TypeVar("T")def remove_if(a: list[T], predicate: Callable[[T], bool]):# TODO: Fill this in.# Test: a = [1, 2, 3, …

Python-scriptlines required to make upload-files from JSON-Call

Lacking experience & routine for Python-programming. Borrowing examples from forums have made a script which successfully makes a JSON-cal (to Domoticz) and generates & prints the derived JSON-…