Python Forum

Full Version: def Class
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
hi,

why is there sometimes an """_""" underscore in the definition of a Class , like this

class C:
    def __init__(self):
        self._x = None

    def getx(self):
        return self._x

    def setx(self, value):
        self._x = value

    def delx(self):
        del self._x
thanks
Methods with double underscores before and after the name are often called "dunders" or "magic methods". These are some methods that Python uses to implement certain behaviors in Python classes.

For example, when you create an instance of a class, Python calls __new__ and then __init__. When you write a class you can provide specific code for Python to excecute when an instance is created by providing your own __new__ or __init__ methods. This code replaces or "overrides" the default method that would be run otherwise. It is very common to see custom __init__ methods. __new__ is used much less frequenly.

After you are comfortable with the basics of Python I suggest you read up on the dunders.
thanks
note that this is design inflused by other language. it's not pythonic. we don't need getters and setters in python in case like this.
Getters and setters are not needed for this simple example, but may be the best solution when setting the value of an attribute is accompanied by some action. For example, setting the value of an LED class object should turn the lamp on. I also like using getters and setters when a class is intimately tied to a user interface.

I would say that getters and setters have as much a place in Python as they do in any other language. They aren't required for accessing attributes, but there are plenty of programming problems where setters, in particular, are a good design choice.

Having said that, I do not like Python properties. They don't work well as a callback and the calling syntax provides no hint that something other than setting the attribute value may be happening.