DEV Community

Cover image for Python | OOP | Classes
Tahir Raza
Tahir Raza

Posted on

Python | OOP | Classes

Recently, I have realised that it is really hard for the beginners to follow the official documentations and most importantly, make sense out of it.

Since Python is one of the easy to use language and a lot of people want to get started with it, I think it is a good idea to share the knowledge in plain English.

For this reason, I am starting this blog post series to explain Python's object oriented model.

Python's object oriented model has the following basic characteristics:

  • It is a mixture of the class mechanisms found in C++ and Modula-3.
  • Classes themselves are objects. This helps for importing and renaming.
  • Class members are public (Methods and Data Members both).
class Example:
    classAttribute = 12345

example = Example()

print(example.i)
Enter fullscreen mode Exit fullscreen mode
  • Every class method needs to have self as the first argument, which is provided implicitly by the call.
class Example:
    classAttribute = 12345

example = Example()

print(example.i)
Enter fullscreen mode Exit fullscreen mode
  • Aliasing: Objects have singularity, and multiple names can be bound to the same object. This is known as aliasing in other languages. Simply speaking, if you pass on object to a function as a argument and change the object inside that function, it will be changed in the main function as well.
from typing import Type

class Counter:
    count = 0

def changeCount(counter: Type[Counter]):
    counter.count = 5

counter = Counter()

print(counter.count)
# 0

changeCount(counter)

print(counter.count)
# 5
Enter fullscreen mode Exit fullscreen mode
  • Most namespaces are currently implemented as Python dictionaries.

Top comments (0)