#!/usr/bin/python3 # -*- coding: utf-8 -*- class MyClass: """This is the more sensible (intended) way to use classes.""" variable = "class variable, not instance variable" def function(self, varin: int) -> None: """Function that can be called from instance""" print("This is a message inside the class.") # The self below exists because it was a parameter # The name self is just convention. # The first variable to a function is a hidden ref to the calling obj. # This variable is only created when the function is called from an instantiated object. self.instancevar = "instance var, not class var" print(varin) # Note the type hint (our custom class) myobjectx: MyClass = MyClass() print(myobjectx.variable) # self is a hidden argument of the object itself, myobjectx myobjectx.function(4) print(myobjectx.instancevar, "exists now") # This is the same, but explicit: MyClass.function(myobjectx, 5) myobjecty: MyClass = MyClass() myobjecty.variable = "changed? no, just makes class hidden" print(myobjecty.variable) print(MyClass.variable) MyClass.variable = "now really changed" print(MyClass.variable) print(myobjecty.variable) print(myobjecty.__dict__) print(MyClass.__dict__) # Then print out both values print(myobjectx.variable) print(myobjecty.variable) # NOTE: If you used a mutable list as a class variable, # and modified it within an instance, similar to how we did above, # it would not behave the same! # self.whatever in a method (function) is for an instance/object variable # ClassName.whatever is a class variable, in a function or not # https://pythontips.com/2013/08/07/the-self-variable-in-python-explained/ # https://www.programiz.com/article/python-self-why # As The Zen of Python goes, "Explicit is better than implicit".