Module (57%)
Section (44%)

The get_internal() method is a class method. This has been signaled to the Python interpreter by using an appropriate decorator. Additionally, the method uses the cls parameter to access the class variable appropriate for the Example class.

Of course, you can use the reference to “Example.__internal_counter”, but this will be inconsistent with the convention and the code loses its effectiveness in communicating its own meaning.

An exception is the __init__() method, which by definition is an instance method, so it can’t use “cls”, and as a result it references the class variable by the “Example” prefix.


Code

class Example:
__internal_counter = 0

def __init__(self, value):
Example.__internal_counter +=1

@classmethod
def get_internal(cls):
return '# of objects created: {}'.format(cls.__internal_counter)

print(Example.get_internal())

example1 = Example(10)
print(Example.get_internal())

example2 = Example(99)
print(Example.get_internal())
{{ dockerServerErrorMsg }} ×
{{ errorMsg }} ×
{{ successMsg }} ×