Python Forum
Unchangeable variables in a class?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Unchangeable variables in a class?
#11
Might could do something like this to keep from setting the value the way I did

@property
    def double(self):
        if self._double != self._value * 2:
            raise AttributeError
        return self._double
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply
#12
(Sep-15-2023, 04:15 PM)menator01 Wrote: Might could do something like this to keep from setting the value the way I did
A much better option is to not define a _double member
class MyNum(object):

    def __init__(self, value):
        self._value = value

    @property
    def value(self):
        return self._value

    @property
    def double(self):
        return self._value * 2
menator01 likes this post
Reply
#13
When an attribute depends on the value of another attribute, and the value of rither attribute can change, I think a method is better choice than using a variable.

Pick a subset of attributes that are needed to compute all attributes. These will become instance variables. Other attributes that are computed from the instance variables become methods. If you want them to look like instance variables you can make them properties.
class MyNum:
      
    def __init__(self, value):
        self.value = value

    @property
    def double(self):
        return self.value * 2

    @double.setter
    def double(self, value):
        self.value = value / 2
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Class variables and Multiprocessing(or concurrent.futures.ProcessPoolExecutor) Tomli 5 3,904 Nov-12-2021, 09:55 PM
Last Post: snippsat
  How to pass variables from one class to another hobbyist 18 10,784 Oct-01-2021, 05:54 PM
Last Post: deanhystad
  Acess variables from class samuelbachorik 3 1,905 Aug-20-2021, 02:55 PM
Last Post: deanhystad
  Class variables menator01 2 2,020 Jun-04-2020, 04:23 PM
Last Post: Yoriz
  Question about naming variables in class methods sShadowSerpent 1 2,024 Mar-25-2020, 04:51 PM
Last Post: ndc85430
  Understanding Class Variables vindo 9 4,066 Jun-05-2019, 08:04 PM
Last Post: Yoriz
  What is the strategy for working with class variables? AlekseyPython 3 3,021 Feb-24-2019, 05:34 AM
Last Post: AlekseyPython
  Base class variables are not accessible Prabakaran141 3 2,831 Oct-31-2018, 07:13 AM
Last Post: buran
  Class Modules, and Passing Variables: Seeking Advice Robo_Pi 21 10,303 Mar-02-2018, 05:22 PM
Last Post: snippsat
  Running Class methods in a loop and updating variables. ujjwalrathod007 3 6,394 Oct-05-2016, 07:11 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020