Python – Class & Objects:
In this tutorial, we will understand about the Classes and Objects in Python. A class is depicted in different syntax as how the functions are defined. Below is the syntax of the Class.
class ClassName: <statement-1> . . . <statement-N>
The statements inside the class are function definitions and also contain other required statements. When a class is created, that creates a local namespace where all data variables and functions are defined.
Below is an example of a class.
>>> class MyFirstClass: ... """ This is an example class """ ... data=127 ... def f(self): ... return 'hello !! you just accessed me'
Accessing the variable data:
Accessing the function f:
<function MyFirstClass.f at 0x7f79c1de5158>
Accessing the doc String:
This is an example class
Now let us see how to create an object. Creation of an object is an instance of the class. Below is how we creating an Object of the class MyFirstClass.
>>> x = MyFirstClass()
In the above line of code, we have created an Object for the class “MyFirstClass” and its name is “x”.
Just trying to access the object name and it gives you information about object.
>>> x <__main__.MyFirstClass object at 0x7f79c1d62fd0> >>>print(x.f) <bound method MyFirstClass.f of <__main__.MyFirstClass object at 0x7f79c1d62fd0>>
Below is how you can access the attributes like data variables and functions inside the class using the Object name, which return some value.
>>>x.f() 'hello !! you just accessed me' >>>x.data 127