Codementor Events

Classes and Methods In Python

Published Jul 05, 2018Last updated Jan 01, 2019

Ever wondered how to create classes and methods in python? Then this is what you’ve been looking for. Explanation suites all languages but the syntax is in python.

All the codes written are in python3.5

If you require any piece in any other python version please enquire in the comments and will be happy to share

OOP is really important in programming, eases out programming and ‘krafting’ out solutions unlike functional programming. Object-oriented programming (OOP) is a programming language model organized around objects rather than “actions” and data rather than logic. Historically, a program has been viewed as a logical procedure that takes input data, processes it, and produces output data.


OOP gets it done ASAP

A real life example OOP (thanks to @sigu for this)
Imagine of two people having lists of things to do: Both decide to have do do lists but one gets “krafty” 😜 in handling out things.
The ordinary guy decides to do things one after the other while the other decides to get people to do things for him at the same time. So if each of the jobs was to be done in 1 hour and they were 5 tasks to be completed, the “krafty” guy would complete all in an hour while the other guy would take 5 solid hours. So which is the best practice? You be the judge 😉

Everything in python is an object

Classes

Classes are declared using the class keyword. A base or parent class is optional; if you do not have one, just use object as the base class. This header line is followed by an optional documentation string, static member declarations, and any method declarations. A class is just like a template though, meaning it can be reused many times. It consists of datatypes and member functions. An object on the other hand is an instance of a class. To access functions(methods) in a class we create an object. If you still don’t get it don’t worry, you will understand much better on the examples.

The following statements define objects:
* They represent entities in your application under development.
* Entities interact among themselves to solve real world problems.

  • -e.g., Person and Car is an entity. Person drives car to move from place to place.


entities interacting among themselves

Classes define objects in attributes and behaviours. Attributes are data members and behaviours manifested via member functions. Classes consist of constructors that provide the initial state of these objects. Classes are like templates and hence can be easily reused (repeated 😅) e.g., class Car will have attributes model and color and member function moveFoward and moveBackwards that defines mobility behaviour of the car.

Methods:

In the OOP world:

** Methods represent the behaviour of the object
** Methods work on attributes and also implement the desired functionality as defined

Below is an example of a class and object(py3.5)

class Person:
 def __init__ (self, name, age):
 self.name = name
 self.age = age
 print(“Hello {},”.format(self.name))

def get_age(self):
 “””This is gets the age of the object “””
 return self.age

def __str__ (self):
 return self.name, self.age

kirwa = Person(‘Kirwa’, 16) # p is an object of type Person 
peter = Person(‘Peter’, 17) # m is also an object of type person

print(type(Person)) # the type class object
print(type(Person.get_age)) # type instancemethod

print(type(Person)) # the type class object
print(type(Person.get_age)) # type instancemethod

The output of the latter code is as follows::

Hello Kirwa,
Hello Peter,
<type 'classobj'>
<type 'instancemethod'>

The code is assigned to two different objects, these will have different attributes(datatypes) as seen on the code examples.

As we have seen a class to be instanced we have to assign it to the class name with parentheses at the end and arguments passed if there are any. e.g.,

kirwa = Person()

The string “hello {Name},” that is displayed on the output is a result of a call to the __init__() method which we did not explicitly have to make. When an instance is created, __init__() is automatically called, whether we provided our own or the interpreter used the default one. Creating instances looks just like calling a function and has the exact same syntax. They are both known
as “callables.” Class instantiation uses the same functional operator as invoking a function or method. 🔚

There is plenty more on Python classes and instances and methods but I couldn’t get to write it all. I will be posting regularly and if you find it interesting please let me know on the comments while you tell me what you want talked on the next blog. If you like it and, You know the drill 😄_{One clap, two clap, three clap, forty}_.

Discover and read more posts from Krafty Coder
get started
post commentsBe the first to share your opinion
Show more replies