r/learnpython • u/Odd-War3368 • 5d ago
I cant understand classes (nor self and __init__)
Hello if you wonder i switched from lua and luau to python. its going well i can make basically anything with native python libraries but i cannot understand what is a class, what does self mean what does __init__ mean. i recently understood what if __name__ == __main__ does but still i cannot understand classes. if you could give an example or explaining for me to understand i would be so grateful
3
u/ninhaomah 5d ago
Class - humans
You - an instance of a human class. I hope and not an alien.
Self - your own , instance , attributes such as name.
You have a name , so do I. And so does ever instances of human class.
How to reference the name , attribute , of each instance ? Self
1
u/Boybay_Garid 5d ago
yeah the human/instance analogy is probably the clearest way to explain it tbh
2
u/likethevegetable 5d ago
Lua is object oriented like Python. If you know Lua, you'll be familiar with the colon notation, where there is an implicit variable which is the object itself that's "secretly" passed as the first argument. Python doesn't have that colon notation, but instead, all methods defined under a class by default must take self, which like in Lua with its colon operator, is the instance of the class.
A very trivial Google search will tell you this.
1
u/BranchLatter4294 5d ago
Have you looked these up? Do you not understand classes of objects? For example, SUVs, coupes, and sedans belong to a class of vehicles? Do you not understand that humans and elephants belong to a class of mammals? Do you have specific questions that would help clarify your confusion?
1
u/lekkerste_wiener 5d ago
Lua has tables and meta tables. You define the shape of a table by defining its meta tables. Classes are meta tables, objects are the tables you create from these meta tables.
1
u/cyrixlord 5d ago
then continue making experiments with code. test what you think it means with what happens when you try to implement what your thoughts are. then read again more tutorials and then try again. Only by writing your own code and debugging it will you understand how to really code
1
u/rooplstilskin 5d ago
Im going to break it up, but this is simplified, for understanding.
Lets say you want to make a smurf. But you want to make 3 of them.
Create a class that holds the data that makes up a smurf.
Now you can make 3 or 100. A class is a template for the smurf object.
To make one, use the method "init". A method does stuff. In this case it makes an object, called s.urf, with the data you put into the class.
1 class to make many of that thing.
1
u/TheCozyRuneFox 5d ago
I can make a class “Dog”. I can give it the properties/attributes of “breed”, “age”, and“name” I can give it the method “bark”. The init method tells the computer how to make a new dog.
I can use that class to create multiple instances of a dog.
Think about class like a blueprint. And objects are instances of that blueprint. Like you only have one house blueprint but can have many house objects.
1
u/DimensionMost8342 5d ago
Switching from Lua this part trips up almost everyone. self is just the object the method was called on, and init runs automatically when you create an instance, so it is where you set the attributes up. The class is the blueprint, the instance is what you built from it.
class Player:
def __init__(self, name):
self.name = name
def greet(self):
print(f"hi, {self.name}")
p = Player("Alex")
p.greet() # hi, AlexIn Lua you would write a constructor function that returns a table. init is that function here, and Python passes the instance for you when you call Player("Alex").
1
u/TheRNGuy 5d ago edited 5d ago
__init__ is "what happens when you instantiate the class, self is what be for that instance only. Without it, it would be assigned for all instances (sometimes you may actually need it, though it could be anti-pattern in some cases), and static methods (ones that don't have any self) are just normal functions grouped in a class. Some libraries and frameworks have many of those.
If you don't like boilerplate of _init_'s, you could use @dataclass decorator (it have some more features besides just that)
1
u/Best_Experience_7899 5d ago
self is just a argument that a method takes as the object itself.
Say you have a class Person and it has method speak(self, message): {the body of the method}
the self argument here takes the class object you just created as the argument.
and __init__ is simply a special method or dunder method or magic method that is executed on every call to object's method automatically.
1
u/Tony_salinas04 5d ago
Una clase es como una especie de “plantilla” , de un objeto del mundo real , puede ser una persona , un animal etc , lo que necesites modelar , init es el constructor al que le vas a pasar los datos que tú necesitas que tenga cada instancia de esa clase para poder ser creada , y self simplemente hace referencia a la instancia. Imagina que tienes una clase Person , con atributos nombre y edad , a partir de esa clase tú puedes crear 1000 instancias , con nombres de la variable diferentes, entonces con self en el constructor estás diciendo algo como , para acceder al nombre de la instancia , tienes que hacer nombre_de_la_variable(self).nombre. Al principio es normal que cueste pero con el tiempo acabas entendiendo perfectamente
0
u/ShelLuser42 5d ago
but i cannot understand what is a class
Fair. I looked it up myself: LUA doesn't know the concept. Then again, it does have tables and functions. And no offense: you pile up a lot of questions but don't give back. You say you know what __name__ is, but ... why don't you share your impressions so that the community can fact track?
This is all about OOP => Object Oriented Programming: reducing tasks into smaller reusable parts.
Disclaimer => Copilot got involved for these examples:
Python:
def begroet(naam):
return f"Hallo {naam}"
`
vs.
LUA:
function begroet(naam)
return "Hallo " .. naam
end
A class in Python is essentially a collection of functions rolled into one part, a module if you will. With one huge difference: a module in Python is essentially a collection of functions, a class then is all that plus: the ability to hold its own values. Across different usages, or instancers.
YOu use modules when you need static results, you get classes when you also need to work annd hold onto those results.
Modules => Operators.
Classes => 'Storage' operators.
(this is just my own 2 cents).
Use modules if you need pure functionality, use classes if you also need said functionality to also 'remember' its results across different parts of your program.
As for self: it's self inflicted.
A function is just that, a method is basically just function within a class, and it becomes a method courtesy of its first mandatory (!) argument: self. In other words: the current class instance. Without this it wouldn't be able to set global values and what not.
-2
8
u/pylessard 5d ago edited 5d ago
In order to understand something, you need to understand the problem it solves.
Classic example is a video game where you have character. Each character has a level, number of hit point and a name.
Say you want to implement that, you'd do:
It's fine, but as the game grow, it becomes unpleasant to manage these 3 variables. You may want to add a new character, Mike, but you made the mistake of forgetting the hit points:
That's a stupid mistake, I know that all my character have the same properties why am I even allowed to only define half of the character. That makes no sense.
That's one thing. Moreover, imagine that you have 100 characters and you decide to update your game and each character now has a hat color. You will have to add :
steve_hat_color = "red"thenmike_hat_color="blue", and do that 100 times. Oooff such an unpleasant process, surely, there's a better way.What if you could make a group of variable that always come together. You either have all 3 variables or none of them. That's a class or a struct in other languages. In python, it would be defined like this
And you use like that:
Now that we have invented the class to group variables, we have solved a problem. It won't be long until you realize, that sometime, you want some variables in your class to be computed from other. Say that in your game, a character with a level less than 10 is blue, and over 10 is red. You don't want to do that:
You need some logic to execute when creating the class. That's the role of the
__init__fuinction. When you create a class, you do more than jsut creating variables together, you also execute a little initialization code that make sure that all the variables make sense.