------>what is a method in Python Programming Language. Moreover, we will learn Python Class Method and Python Object. Along with this, we will study the python functions.
1. Python Method – Objective
Introduction:
"Python is an object-oriented language"
- This means that it can deal with classes and objects to model the real world. A
- Python method is a label that you can call on an object; it is a piece of code to execute on that object
Python Class Method:
- Python Class is an Abstract Data Type (ADT). Think of it like a blueprint.
- A rocket made from referring to its blueprint is according to plan.
- It has all the properties mentioned in the plan, and behaves accordingly. Likewise, a class is a blueprint for an object.
- To take an example, we would suggest thinking of a car
Here, this is an object of the class Car, and we may choose to call it ‘car1’ or ‘blackverna’.
>>> class Car:
def __init__(self,brand,model,color,fuel):
self.brand=brand
self.model=model
self.color=color
self.fuel=fuel
def start(self):
pass
def halt(self):
pass
def drift(self):
pass
def speedup(self):
pass
def turn(self):
pass
Python Objects
- A Python object is an instance of a class. It can have properties and behavior.
- We just created the class Car. Now, let’s create an object blackverna from this class. Remember that you can use a class to create as many objects
>>> blackverna=Car('Hyundai','Verna','Black
- This creates a Car object, called blackverna, with the aforementioned attributes.
- We did this by calling the class like a function (the syntax).
- Now, let’s access its fuel attribute
An interesting discovery–
- When we first defined the class Car, we did not pass the ‘self’ parameter to the five methods of the class.
- This worked fine with the attributes, but when we called the drift() method on blackverna, it gave us this error:
Traceback(most recent call last):
File “<pyshell#19>”, line 1, in <module>
blackverna.drift()
TypeError: drift() takes 0 positional arguments but 1 was given
- From this error, we figured that we were missing the ‘self’ parameter to all those methods.
- Then we added it to all of them, and called drift() on blackverna again. It still didn’t work.