Class in python
Hello, I'm new in repl.it but I am a bit experienced in python. But I am always confused when some tells me about class in python. Can some one help me with this?
Sure, classes in python hold data sort of like a dictionary, but different. Basic classes look like this:
class Joe(): name = "Joe" age = 10 print(joe.age) # will will get 10 printed to the console
The reason why classes can seem to be complicated is because there is a special function you can make inside of a class called
__init__() Inside of init we have self as the first argument, than any other arguments we want to add to our object. We can then use that class to make lots of other objects.
That description is pretty bad but this should explain it. Suppose for some reason in a game, we want to make a bunch of cars, each of these cars will have a color, model, and max_speed. Instead of making a class for each car, or a dictionary to hold the data, we can make a class using init and then reuse that class.
class car(): def __init__(self, color, model, max_speed): # note these arguments could be x,y,z if we wanted them to be self.color = color self.model = model self.m_speed = max_speed
Now we can use that class to create other cars
myCar1 = car("red", "ford", 30) myCar2 = car("blue", "honda", 50) if myCar1.m_speed > myCar2.m_speed: print(True) else: print(False) # false will be printed to the console.
That isn't really the best of explanations, but here's a repl you can take a look at if you want to see some actual code using classes.
And if you have any other questions, go ahead and ask my and I'll try to answer them.