Member-only story
How to Write a Python 3 Class
Beginner’s Guide to Python 3 objects.
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 = 12my_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 xmy_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…