- #1
fog37
- 1,568
- 108
Hello,
I get that everything (almost?) in Python is an object. Objects are instances of classes with associated attributes (i.e. characteristics, properties, features) which are essentially variables. Objects also have associated methods (i.e. functions that act on the object or make the object do certain things). Each class has its own innate methods.
That said:
The difference: at line #17 we created an object and assigned values to its attributes at the moment of instantiation. In the first case instead (line #3 and line #4) we assigned the value to the attribute model not when we created the object but when we created the class...
Is that correct? And is that why using the method __init__ is useful when creating objects?Thank you for any clarifications!
I get that everything (almost?) in Python is an object. Objects are instances of classes with associated attributes (i.e. characteristics, properties, features) which are essentially variables. Objects also have associated methods (i.e. functions that act on the object or make the object do certain things). Each class has its own innate methods.
That said:
- If "everything" is an object, does that mean that even a simply integer, float, or list that we create at the prompt is an object? From what class do these objects originate?
- The built-in functions from the Python standard library, like the functions like print() or input(), are therefore methods, not objects, correct? Methods are not objects. To what class do the built-in functions/methods belong to?
- When creating a class, the special method __init__ (the constructor) is almost always used to create objects. But I don't think it is always needed to create an object from a class. For example, let's consider the class Car and create a single object from it:
Code:
# Create a simple class with a single attribute
class Car():
model = "Honda"
mycar=Car() # Here we instantiate an object called mycar from the class. This object has a single attribute already specified.
print(mycar.model) # we use the dot notation to view the attribute associated to the object mycar.
# We could write the same class Car with 3 attributes in a different way using the __int__ method:
class Car():
def __init__(self, make, model, color) : # make, model, color are threeattributes
self.make = make
self.model = model
self.color = color
mycar= Car(Nissan,Altima, green) #this line creates an object called mycar and we assign the values to the attributes at this moment
The difference: at line #17 we created an object and assigned values to its attributes at the moment of instantiation. In the first case instead (line #3 and line #4) we assigned the value to the attribute model not when we created the object but when we created the class...
Is that correct? And is that why using the method __init__ is useful when creating objects?Thank you for any clarifications!