Classes and Object-oriented Programming in Python

05 min read

Classes are the primary mechanism used to create data structures and new kinds of objects. A clas defines a set of attributes associated with a collection of objects known as instances. These attributes typically include functions, which are known as methods, variables, which are known as class variables, and computed attributes, which are known as properties. Classes are defined using class statement. The body of a class contains a series of statements that are executed when the class is first defined. Let us now look at a simple example,

class Account(object):

          "A simple class"

          num_accounts = 0

          def__del__(self):

                    Account.num_accounts = -1

         def deposit(self amt):

                   "Add to the balance"

                    self.balance +=amt

                    return self.balance

The objects are created during the execution of the class body are placed into a class object that serves as a namespace. For example, the members of the Account class are accessible as Account,num_accounts, Account.__del__     etc.

The function defined inside a class are known to be called as methods. An instance method is a function that operates on an instance of a class, which is passed as the first argument. By convention, this argument is called self, although any legal identifier name can be used. In the above example, deposit() is an example of an instance method.

If a method is defined with an @staticmethod decorator, it is called a static method. A static method is merely a function that is packaged with the class but is not associated with any instances. Since no instance is involved, a static method does not have self-parameter. If a method is defined with an @classmethod decorator, it is called a class parameter. A class method receives the class object itself as the first argument, which is called cls by convention.

Syntax:

class FACEPrep(object):

             @staticmethod / @classmethod

             def placements(x): 
.
.
.

 

POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error