Python classes and objects
Python is a object oriented programming language. In python mostly everything is an object with its properties(variables) and methods(functions).
Similarly Class is a blueprint of that object.
Create a class:
For creating a class we use a class keyword followed by the class name.
Body of class
# Define a class
Defining a new Tourist class
def __init__(self, name, age):
self.name = name
self.age = age
## Instance method def sayHello(self):
print("Hello, my name is " + self.name)
print("Hello, my ageis " + str(self.age))# Object instantiation
t1 = Tourist("John", 36)
After run the above code the output will be
Hello, my name is John
Hello, my age is 36
<__main__.Tourist object at 0x000001360A791730>
In the above example:
In python all classes have __init__() is called initialization method or class constructor. It calls when you create a object of Tourist class.
There are two statements using self variable:
- self.name = name creates an attribute called name and assign value to its name parameter
- self.age= age creates an attribute called age and assigns to it the value of the age parameter.
All Tourist objects have attributes name and age but have different value of name and age depends on the Tourist objects.
Second method sayHello() is normal function or instance method inside Tourist class and can only be called by instance of the class. It return two strings displaying name and age of the tourist.
To create instances of class, you call the class with its name and pass same arguments __init__() accepts.
t1 = Tourist("John", 36) line means t1 is object of Tourist class at memory location 0x000001360A791730. This memory address indicates that where Tourist object t1 is stored in yours computer memory.
If you create a new instance that will store in different memory address.
Lets create another object
t2 = Tourist(“Smith”, 27)
Hello, my name is Smith
Hello, my name is 27
<__main__.Tourist object at 0x000001360A7A5460>
You can see that new Tourist object located at different memory address because its a new instance and its completely new from the first Tourist object t1 that you instantiated.
Don’t worry, you can also check in different way.
t1 == t2
Above line we compare t1 and t2 object using == operator, the result is false. t1 and t2 both are instances of Tourist class but they are distinct objects in computer memory.
Points to remember:
- To instantiate object of class you need to provide arguments that's necessary. If you don’t the Python raises a TypeError:
Let’s create another Tourist object and assign it to t3.
t3 = Tourist()
TypeError Traceback (most recent call last)
<ipython-input-13-c4ac6fc04fcc> in <module>
----> 1 t3 = Tourist()
TypeError: __init__() missing 2 required positional arguments: 'name' and 'age'
Thanks for reading……
Feel free to leave a comment or share this post. Follow me for future posts.