Python OOPs


Examples


Others


Python OOPs - Classes and Objects


  • Python is an object-oriented programming language.
  • Class is a user-defined datatype it has collection of variables and functions.
  • An object is an instance of a class which is used to access the members of the class.

Creating a Class in Python:

We can create class using the keyword class.

Syntax
class Data:
    def sample(self):
        print("Hello World")
  • Class methods must have an parameter named self.
  • The self parameter is used to represent the instance of the class, which used to access variables and methods that belongs to the class.

Creating an Object in Python:

We can use the class name to create an objects then access the members of the class.

Syntax
obj=Data()
obj.sample()

The following example shows, how to Create Class and objects with methods

Example
class Data:
    def get_name(self):
        self.name=input("Enter Your Name : ")
    def print_name(self):
        print("Name : ",self.name)
obj=Data()
obj.get_name()
obj.print_name()
Output
Enter Your Name : Ram
Name :  Ram

Constructors in Python