Member-only story

How to Write a Python 3 Class

Beginner’s Guide to Python 3 objects.

Oren Cohen
2 min readMay 26, 2021

The way we write Python classes is very straightforward. Here’s an example:

class MyClass:
...

That is the core definition of a class.

Init Function

Any class in python which uses non-static methods needs an init function. This is how you write one:

class MyClass:
def __init__(self):
...

Every time you create a new object from this class, that method will run, and the generated object will have all the methods and members defined in the class. Here’s a complete example:

class MyClass:
def __init__(self):
self.x = 12
my_obj = MyClass()
# print(my_obj.x) will print 12.

Methods

A class can define methods that the object will offer anyone using it. Here’s an example:

class MyClass:
def __init__(self):
self.x = 12
def get_x(self):
return x
my_obj = MyClass()
# print(my_obj.get_x()) will print 12.

Static Methods

Static methods are methods you can use on the class itself. Using them on actual instances of the class might create…

--

--

Oren Cohen
Oren Cohen

Written by Oren Cohen

Software Engineer and Blogger. He/Him. Contact me: oren@thegeekwriter.com Newsletter: https://theorencohen.com Geek Peek: https://geekpeek.blog

No responses yet