Learn Simpli

Free Online Tutorial For Programmers, Contains a Solution For Question in Programming. Quizzes and Practice / Company / Test interview Questions.

Classes and Objects in pythonClasses and Objects in python

In this chapter you will learn about, Classes and Objects in python. In the previous chapters, we have studied the basics in the python. Now its time to jump more into the python, as we know the classes are the heart of any object-oriented programming languages.

How to create a class in python?

  1. We can create a class with the help of the keyword class.
  2. Then followed by the class name
  3. The name of the class should be in camel case
  4. Then followed by the colon
  5. Every class will have a special method called __init__
  6. The init method allows you to create an instance of the actual object
  7. You can pass n number of parameters to the init method
  8. The first param is self to the init method
  9. The self connects all the parameters to the self
  10. Afterwards, you can define any number of methods

Now let’s write an example for creating the class and accessing the method which is defined in the class

class Employee:
  def __init__(self, name, email):
    self.name = name
    self.email = email

  def greetEmployee(self):
    print("Good morning " + self.name)

employeePerson = Employee("Stark", '')
employeePerson.greetEmployee()

# output 
# Good morning Stark

How to create an object of class?

Once we define the class and method inside the class, then we can create an object of the same class, an object is an instance of the class.

class Employee():
  def __init__(self, name, email):
    self.name = name
    self.email = email

  def greetEmployee(self):
    print("Good morning " + self.name)

employeePerson = Employee("Stark", '')
employeePerson.greetEmployee()
print(type(employeePerson))

# output 
# Good morning Stark
# <class '__main__.Employee'>

As we can see in the above code snippet, the object employeePerson is an instance of a class Employee.

One thought on “Classes and Objects in python

Comments are closed.