Classes and Objects

What Are Classes and Objects?

  • Python is an object-oriented programming language, where almost everything is an object, with its properties and methods.
  • A class is like a blueprint for creating objects. It defines a set of attributes and methods that the created objects will have.

Creating a Class:

  • Use the class keyword to create a class.

    python
    class MyClass:
        x = 5
    

Creating an Object:

  • Once you have a class, you can create an object from it.

    python
    p1 = MyClass()
    print(p1.x)  # Output: 5
    

The __init__() Function:

  • All classes have an __init__() function, which is executed when the class is being initiated. This function is used to assign values to object properties or perform other initializations.

    python
    class Person:
        def __init__(self, name, age):
            self.name = name
            self.age = age
    
    p1 = Person("John", 36)
    print(p1.name)  # Output: John
    print(p1.age)   # Output: 36
    

The __str__() Function:

  • The __str__() function controls what should be returned when the class object is represented as a string.

    python
    class Person:
        def __init__(self, name, age):
            self.name = name
            self.age = age
    
        def __str__(self):
            return f"{self.name}({self.age})"
    
    p1 = Person("John", 36)
    print(p1)  # Output: John(36)
    

Object Methods:

  • Objects can also contain methods, which are functions that belong to the object.

    python
    class Person:
        def __init__(self, name, age):
            self.name = name
            self.age = age
    
        def myfunc(self):
            print("Hello my name is " + self.name)
    
    p1 = Person("John", 36)
    p1.myfunc()  # Output: Hello my name is John
    

The self Parameter:

  • The self parameter is a reference to the current instance of the class and is used to access variables that belong to the class. It can be named anything, but it must be the first parameter of any function in the class.

    python
    class Person:
        def __init__(mysillyobject, name, age):
            mysillyobject.name = name
            mysillyobject.age = age
    
        def myfunc(abc):
            print("Hello my name is " + abc.name)
    
    p1 = Person("John", 36)
    p1.myfunc()  # Output: Hello my name is John
    

Modifying Object Properties:

  • You can modify properties on objects.

    python
    p1.age = 40
    

Deleting Object Properties:

  • You can delete properties on objects using the del keyword.

    python
    del p1.age
    

Deleting Objects:

  • You can delete objects using the del keyword.

    python
    del p1
    

The pass Statement:

  • If a class definition is empty, use the pass statement to avoid getting an error.

    python
    class Person:
        pass
    

Exercises:

  1. Create a Simple Class and Object:
    • Create a class named Animal with a property species. Create an object of this class and print the species.

      python
      class Animal:
          def __init__(self, species):
              self.species = species
      
      a1 = Animal("Dog")
      print(a1.species)  # Output: Dog
      
  2. Add Methods to the Class:
    • Add a method to the Animal class that prints a greeting message including the species. Create an object and call this method.

      python
      class Animal:
          def __init__(self, species):
              self.species = species
      
          def greet(self):
              print("Hello, I am a " + self.species)
      
      a1 = Animal("Dog")
      a1.greet()  # Output: Hello, I am a Dog
      
  3. Modify and Delete Properties:
    • Modify the species property of the object and print the updated property. Then, delete the property and try to print it again.

      python
      class Animal:
          def __init__(self, species):
              self.species = species
      
      a1 = Animal("Dog")
      a1.species = "Cat"
      print(a1.species)  # Output: Cat
      del a1.species
      # print(a1.species)  # This will raise an AttributeError
      

Summary:

  • Classes and objects are fundamental concepts in object-oriented programming in Python. Understanding how to create and use classes and objects will help you write more organized and reusable code. Practice creating classes, objects, and methods to get comfortable with these concepts