In Python, to write the blueprint for a group of objects, or a ‘class’, we must follow a certain syntax…
class Class_name: attribute1 = value1, attribute2 = value2
Here, ‘class_name’ should be replaced with the name of the class, and all the default attributes (or variable values) should be set below the class’s name, as shown. For example…
class Car: type = “sedan”, year = 2001, mileage = 30500
Here, I have created a ‘Car’ class with three attributes set to default values: type, year, and mileage.
After you have created the blueprint for objects (i.e. the class), to actually create an object we must “instantiate” it (i.e. make an instance of it). To do so, all we do is…
object_name = class_name()
“object_name” should be replaced by the unique name you want to give to this particular object of the class. “class_name” should be the name of the class, obviously. Do note, the “()” are a must. We’ll go over what they do in a later lesson. An example of an object would be…
mercE330 = Car() print(mercE330)
<__main__.Car object at 0x10529f250>
This output isn’t particularly appealing, I’ll admit. We’ll get to how to actually access attributes next!
To access an attribute of a specific object of a class, we use ‘.’ notation. Basically, ‘object_name.attribute_name’. So, to access the year of the car object we created earlier…
On top of accessing these attributes, you can also edit their values using ‘.’ notation. Just use the assignment operator (‘=’)...
mercE330.year = 2005 print(mercE330.year)
It’s that simple!
Aside from attributes, objects in python can also have their own functions that act on the data of the object. For example, with the car, we could have a function to drive, and add miles to ‘mileage’ as we drive. First, we’ll need to add the function (also called a method) to the class definition. In Python, the first argument of all object methods is the object itself, so we typically write ‘self’ as a placeholder for the object itself. Any other arguments are entered separated by a comma after the ‘self’. So…
class Car: type = “sedan” year = 2001 mileage = 30500 drive(self): self.mileage = self.mileage + 5
To actually get the object to run its method, (the method will only run for this object, not all objects of the class) we must call the method, like any other function. So…
print(mercE330.mileage) mercE330.drive() print(mercE330.mileage)
Voila! The drive method worked, and the object successfully changed its own attributes after its method was called. That’s the basics of object attributes and methods. Moving on to the initialization of objects!