Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python Prevent Re-assignment of a Class Method Outside The Class

I want some of my class methods to be not re-assignable outside (or both outside and inside) of the class. As functions are objects too in python, is it possible to accomplish what I want? Here is the method;

def x(self):
    """Return x, the horizontal distance between the shape and the leftmost of the screen, in pixels"""
    return self.__x

Now outside of the class, it is easy to mess with this method;

shape = Shape(10, 20)
shape.x = 30
print(shape.x)  # Prints 30
print(shape.x())    # TypeError: 'int' object is not callable

Is it possible to prevent this kind of assignment of class methods?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You could override the __setattr__ method to check to see if the key is in a forbidden list for example…

class Shape:
    def __init__(self, a, b):
        self.__x = a
        self.__y = b

    def x(self):
        return self.__x

    def __setattr__(self, key, value):
        if key in ('x', 'y'):
            raise TypeError(f"You can't change {key}")
        super(Shape, self).__setattr__(key, value)


shape = Shape(11, 20)
shape.z = 100  # OK
print(shape.z)
print(shape.x())
shape.x = 30  # raise an exception
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading