Python Forum
The function of double underscore back and front in a class function name?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
The function of double underscore back and front in a class function name?
#5
Using __init__ in classes is fundamental for initializing(getting data in from outside) to the newly created objects.
While it's true that you can manually set attributes on an instance as in your second example.
Also try len(a) and see that it won't work as that what __len__ dos in my class.

Classes with an __init__ method are generally more readable and maintainable.
Anyone reading your code can easily understand what attributes an instance of the class is expected to have and what initial state it will be in.

Consistency:
Using __init__ ensures that every instance of the class is initialized consistently.
Without __init__ you rely on manually setting attributes after object creation,
which can lead to errors or inconsistencies if some attributes are forgotten or mistyped

So can also add documentation and eg type hint to make even more clear what the class dos.
Then will see when create a object that it need a list of int and help(MtList) will work.
class MyList:
    """A custom list class that encapsulates a list and provides
    special methods to interact with its data.
    """
    def __init__(self, data: list[int]):
        self.data = data

    def __contains__(self, item: int) -> bool:
        """Check if the item exists in the data."""
        return item in self.data

    def __len__(self) -> int:
        """Return the number of items in the data."""
        return len(self.data)
To give one more example the more realistic as there often several values that you what to initialized class with.
class Car:
    """Represents a car with specific attributes and capabilities."""
    def __init__(self, color: str, mileage: float, fuel_efficiency: float):
        self.color = color
        self.mileage = mileage
        self.fuel_efficiency = fuel_efficiency

    def calculate_gas_usage(self, distance: float) -> float:
        """Calculate the amount of gas used over a given distance."""
        return distance / self.fuel_efficiency

    def __repr__(self):
        return f"Car(color={self.color!r}, mileage={self.mileage}, fuel_efficiency={self.fuel_efficiency})"

    def __str__(self):
        return f"A {self.color} car with {self.mileage} miles, fuel efficiency {self.fuel_efficiency} mpg."
Use this class.
>>> my_car = Car('red', 10, 14.5)
>>> # This work because of __repr__
>>> my_car
Car(color='red', mileage=10, fuel_efficiency=14.5)
>>> # This work because of __str__
>>> print(my_car)
A red car with 10 miles, fuel efficiency 14.5 mpg.
>>> my_car.calculate_gas_usage(100)
6.896551724137931
>>> help(Car)
Help on class Car in module __main__:

class Car(builtins.object)
 |  Car(color: str, mileage: float, fuel_efficiency: float)
 |
 |  Represents a car with specific attributes and capabilities.
 |
 |  Methods defined here:
 |
 |  __init__(self, color: str, mileage: float, fuel_efficiency: float)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |
 |  __repr__(self)
 |      Return repr(self).
 |
 |  __str__(self)
 |      Return str(self).
 |
 |  calculate_gas_usage(self, distance: float) -> float
 |      Calculate the amount of gas used over a given distance.
Reply


Messages In This Thread
RE: The function of double underscore back and front in a class function name? - by snippsat - Feb-19-2024, 11:11 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  front-end js and back-end python 3lnyn0 0 1,041 Jun-03-2022, 08:51 PM
Last Post: 3lnyn0
  TimeOut a function in a class ? Armandito 1 1,736 Apr-25-2022, 04:51 PM
Last Post: Gribouillis
  Calling a class from a function jc4d 5 1,948 Dec-17-2021, 09:04 PM
Last Post: ndc85430
  Exit function from nested function based on user input Turtle 5 3,058 Oct-10-2021, 12:55 AM
Last Post: Turtle
  a function common to methods of a class Skaperen 7 2,742 Oct-04-2021, 07:07 PM
Last Post: Skaperen
  Tuple generator, and function/class syntax quazirfan 3 4,059 Aug-10-2021, 09:32 AM
Last Post: buran
Question Stopping a parent function from a nested function? wallgraffiti 1 3,753 May-02-2021, 12:21 PM
Last Post: Gribouillis
Question exiting the outer function from the inner function banidjamali 3 3,683 Feb-27-2021, 09:47 AM
Last Post: banidjamali
  Struggling for the past hour to define function and call it back godlyredwall 2 2,296 Oct-29-2020, 02:45 PM
Last Post: deanhystad
  Passing argument from top-level function to embedded function JaneTan 2 2,326 Oct-15-2020, 03:50 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

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