Python Object Oriented Programming | Methods

Classes can have other methods that add functionality to them. All methods must have self as their first parameter. These methods are accessed using the same dot syntax as attributes.

Example:

class Motor:
	def __init__(self, name, color):
		self.name = name
		self.color = color

	def broken(self):
		print("brrr ... pfff!")

piaggio = Motor("Piaggio", "orange")
print(piaggio.name)
piaggio.broken()

The terminal output will be:

ddn_ro@linux:~/Desktop$ python file.py
Piaggio
brrr ... pfff!
ddn_ro@linux:~/Desktop$

Classes can have class attributes, created by assigning variables within the body of the class. These can be accessed either from instances of the class, or the class itself.

Example:

class Motor:
	engine = 125
	def __init__(self, name, color):
		self.name = name
		self.color = color

	def broken(self):
		print("brrr ... pfff!")

piaggio = Motor("Piaggio", "orange")
print(piaggio.engine)
print(Motor.engine)

The terminal output will be:

ddn_ro@linux:~/Desktop$ python file.py
125
125
ddn_ro@linux:~/Desktop$

Note:
Class attributes are shared by all instances of the class.
Trying to access an attribute of an instance that isn’t defined causes an AttributeError. This also applies when you call an undefined method.

Example:

class Motor:
	engine = 125
	def __init__(self, name, color):
		self.name = name
		self.color = color

	def broken(self):
		print("brrr ... pfff!")

piaggio = Motor("Piaggio", "orange")
print(piaggio.engine)
print(Motor.engine)
print(piaggio.price)

The terminal output will be:

ddn_ro@linux:~/Desktop$ python file.py
125
125
Traceback (most recent call last):
  File "file.py", line 13, in 
    print(piaggio.price)
AttributeError: Motor instance has no attribute 'price'
ddn_ro@linux:~/Desktop$

As you can see it printed the engine size of piaggio and the engine size of Motor but it didn’t print the price of piaggion because there is no such attibute!

Leave a Reply