Search code examples
pythonclassmethodsdefined

Is it possible to combine methods? (Python, defining class methods)


I'm currently working through a Python tutorial and after watching the lesson about creating a class and defining its methods I was wondering if it is possible to combine methods.

So instead of using:

class Coordinates:
    def point1(self):
        print(x)

    def point2(self):
        print(y)

    def point3(self):
        print(z)

x = 5
y = 4
z = 9

Coordinates.point1(x) / Coordinates.point2(y) / Coordinates.point3(z)

I could instead use this to call for either x, y or z:

class Coordinates:
    def point(self):
        print(x or y or z)


x = 5
y = 4
z = 9

Coordinates.point(x/y/z)

If I do that though I always get x's number 5 on the terminal no matter if I use x, y or z as self.

Thanks for any input :)


Solution

  • You don't want separate functions for getting each of the x, y & z values.

    Firstly you could consider having no functions at all by directly accessing the instance variables like this:

    class Coordinates:
        def __init__(self, x, y, z):
            self.x = x
            self.y = y
            self.z = z
    
    C = Coordinates(10, 20, 30)
    
    print(C.x, C.y, C.z)
    

    Another option would be to use properties. For example:

    class Coordinates:
        def __init__(self, x, y, z):
            self._x = x
            self._y = y
            self._z = z
        @property
        def x(self):
            return self._x
        @property
        def y(self):
            return self._y
        @property
        def z(self):
            return self._z
    
    C = Coordinates(10, 20, 30)
    
    print(C.x, C.y, C.z)
    

    In this way you can exert control over what gets returned for any given value.

    You could even make your class behave like a dictionary as follows:

    class Coordinates:
        def __init__(self, x, y, z):
            self.d = {'x': x, 'y': y, 'z': z}
    
        def __getitem__(self, k):
            return self.d.get(k, None)
    
    
    C = Coordinates(10, 20, 30)
    
    print(C['x'], C['y'], C['z'])
    

    In this last example you have just one function involved in the acquisition of a variable but even then you don't call it explicitly