+ 2

Difference class and object

What's the difference between class and object? And how we can define attribute and variables base on them?

5th Aug 2020, 10:21 AM
Sarah
Sarah - avatar
3 Respostas
+ 1
Sa Ta start_engine(self) is a method, a function is outside of a class, Yes, a method can have any amount of values they are called arguments when defining the function and parameters when calling the function, for example def greet(Type, Name): # type and Name are called arguments print(Type + Name) # here they are called parameters greet('Hello', 'Sa Ta') Other than that it's correct
5th Aug 2020, 11:22 AM
12ksins
12ksins - avatar
+ 5
An object is an instance of a class That means for example Class A: # a class def __init__(self, value): # a method self.Value = value # an attribute for the instance O = A(5) # value = 5 Here the Object O is an instance of the class A Defining attributes is just like variables (attributes are class variable) but in a class for example Class A: attribute = 5 # can be any name print(A.attribute) # outputs 5
5th Aug 2020, 10:37 AM
12ksins
12ksins - avatar
+ 1
Thanks a lot So Are my comments in below code correct? class Car: # a class wheels = 4 # attribute def __init__ (self, color): # a method, can we have more values here? self.color = color # an attribute self.running = False # another attribute def start_engine(self): # a function? self.running = true #attribute print("Vroom!) my_car = Car("red) #object? print(my_car.color)
5th Aug 2020, 11:15 AM
Sarah
Sarah - avatar