LEARNING PYTHON

BASICS & OBJECT-ORIENTED PROGRAMMING WITH PYTHON
3

PYTHON 3

EASY

last hacked on Jun 10, 2018

## HI ALL -- I AM LOOKING FOR CONTRIBUTORS :) ---

Python is an object-oriented programming language. Object-oriented programming (OPP) focuses on creating reusable patterns of code.

Class

A class is a blueprint or prototype of an object. Defines set of characteristics that characterize an object.

We define classes by using the class keyword.

class Monkey:
  def eat(self, food):
    print("Monkey eats %s.", % food)

  def run(self):
    print("Monkey runs.")

The eat and run functions are methods because they are defined within a class. Both methods take the argument self, which means that these functions will take the object instances of this class, as a parameter.

Object

An object is an instance of a class.

Let's instantiate the Monkey class, making an object called pedro:

pedro = Monkey()

pedro is now an object of class Monkey, which means that we can execute its eat and run methods:

pedro.eat()
pedro.run()

Notice that we use the dot operator . to call the object's methods. Also, we don't need to include a parameter -- since we specified self as the argument, the object pedro is used as a parameter automatically. Neat.

The Constructor Method

The constructor method, __init__, is used to initialize data, and it runs as soon as an object is instantiated.

class Monkey:
  def __init__(self, name):
    self.name = name
    print(self.name)

References

How To Construct Classes and Define Objects in Python 3 by Digital Ocean


COMMENTS







keep exploring!

back to all projects