3 Antwoorden
0
The __init__() method is called whenever a new object is instantiated from a class. You would typically use this method to set up any attributes for the object, as it is where arguments for creating the object get handled. You can also use it to do any other kind of startup code. For example:
class Sandwich:
def __init__(self, meat):
print(f“A {meat} sandwich was born!”)
self.meat = meat
burger = Sandwich(meat = “ground beef”)
# A ground beef sandwich was born!
hamsandwich = Sandwich(meat = “ham”)
# A ham sandwich was born!
0
__init__ is a function under a class/object that lets you create an instance from that object with extra arguments you add in the __init__.
Eg. you have a ball object and you want to have many balls with each ball having a different color and size. The main ball class would be like this:
class Ball:
def __init__(self, color, size):
#self argument must be added in the __init__ function declaration as it represents the current instance self, then you can manipulate your args as you want
self.color = color #sets the current ball instance's color attribute to the color
self.size = size
self.is_alive = True #custom attribute just for fun
#the __init__ function isn't supposed to return something as it already returns the newly created instance
def pop(self): #some function
self.is_alive = False
def __str__(self):
return f"Ball (size={self.size}, color={self.color}) {['!Dead¡', 'Alive!'][int(self.is_alive)]}" #returns the string representation
0
here's code in action:
https://sololearn.com/compiler-playground/c7FmWuwkkJbf/?ref=app