Python Classes And Object Orientated Design

Date Published:
Last Modified:

Since Python v3.3, you can use both the `@staticmethod` and `@abstractmethod` decorators on the same class function (and the `@abstractstaticmethod` decorator has been depreciated).

import abc

class MyClass:

    def my_func():

Checking If A Class Is A Subclass Of Another

You can check if one class is a sub-class of another with the issublass() function:

class ParentClass:

class ChildClass(ParentClass):

class StandaloneClass:

print(issubclass(ChildClass, ParentClass))
# stdout: True

print(issubclass(StandaloneClass, ParentClass))
# stdout: False

# Works with variables which are assigned to a class too
my_class = ChildClass
print(issubclass(my_class, ParentClass))
# stdout: True

Class Variables

In Python, classes can be assigned variables, either statically or dynamically. The important difference between assigning variable to A class and assigning variables to an INSTANCE of a class is that class variables are shared between all variables/instances of that class, while instance variables are unique to that particular instance of the class.

class TestClass:

# Create two class variables (not here that we are NOT)
# creating instances, there are no brackets () at the end)
test_class_1 = TestClass
test_class_2 = TestClass

# Assign a value to a class variable
test_class_1.my_var = 2

# The other class variable now has this value too!
# stdout: 2

test_class_2.my_var = 3
# The original classes variable has changed, as the variable is shared
# between all identical class objects
# stdout: 3

Like this page? Upvote with shurikens!

Related Content:


comments powered by Disqus