Python Classes And Object Orientated Design

Article by:
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).

1
2
3
4
5
6
7
8
import abc

class MyClass:

    @staticmethod
    @abstractmethod
    def my_func():
        pass
NOTE

You have to make sure to specify @staticmethod before @abstractmethod or it will not work.

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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class ParentClass:
    pass

class ChildClass(ParentClass):
    pass

class StandaloneClass:
    pass

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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class TestClass:
    pass

# 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!
print(test_class_2.my_var)
# stdout: 2

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

Authors

Geoffrey Hunter

Dude making stuff.

Creative Commons License
This work is licensed under a Creative Commons Attribution 4.0 International License .

Related Content:

Tags

comments powered by Disqus