Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
def Class
#1
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
Reply
#2
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.
Reply
#3
thanks
Reply
#4
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.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
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.
Reply


Forum Jump:

User Panel Messages

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