2

I was wondering if there is a preferred method to refer to a value from within a class.

For example in the following code:

class Coordinate(object):

    def __init__(self, x):
        self.x = x

    def getX(self):
        return(self.x)

    def transform(self, dx):
        return self.x - dx

When I want to use x somewhere in another method of the Coordinate class, for example in the transform method, what is the preferred way to refer to x? Is it with self.x or self.getX(), such that transform becomes:

    def transform(self, dx):
        return self.getX() - dx

I understood that using getX() is preferred when trying to get the value x from outside the class. Thus:

>>> c = Coordinate(13)
>>> print(c.getX()) # Preferred method
13
>>> print(c.x) 
13
Roald
  • 2,459
  • 16
  • 43
  • I would not call it a duplicate of that question @CoryKramer. That question is about getting and setting values from _outside_ a class. Mine is about getting class variables from _inside_ a class. – Roald Sep 05 '17 at 14:30
  • The exact same principles are discussed in that link, regardless of if you are within or outside the class. You can use the decorators if you need extra logic besides just setting and getting (validation, logging, etc). – Cory Kramer Sep 05 '17 at 14:55
  • @CoryKramer So if I understand it correctly, you do not define your own getter and setter methods. If you really want to write your own getter and setter methods, you can do so using the [Python Property](https://docs.python.org/3/library/functions.html#property). The preferred method is to access the variable `x` from inside or outside the class with a simple `self.x` or `c.x` respectively. This is odd, because (if I recall correctly) in the MITx python course on edX.org, they say it is better to define your own getter and setter methods. – Roald Sep 05 '17 at 15:22

0 Answers0