When you access an attribute with self, Python first looks for it in the instance's namespace. If it doesn't find it there, it then checks in the class namespace (and subsequently in the namespaces of its base classes, if any).
Define a Class
class MyClass:
# class definition
class MyClass(ClassToInheritFrom):
# class definition
Member Variables
Define class attributes.
class MyClass:
class_attribute_1 = 0
@classmethod
def class_method(cls):
# Change value of an existing class attribute.
cls.class_attribute_1 = 2
# Create a new class attribute.
cls.class_attribute_2 = 4
Define instance variables.
class MyClass:
self.myvar1 = 2
def __init__(self):
self.myvar2 = 6
Methods
Class methods, instance methods, and static methods:
class MyClass:
@classmethod
def class_method(cls, arg1, arg2):
# Must only pass `cls`.
# You can't pass `self` (the instance) to
# a class method because there's no instance.
print("This is a class method")
def regular_method(self, arg1, arg2):
# Must only pass `self`.
print("This is a regular method")
@staticmethod
def static_method(arg1, arg2):
# Cannot pass `cls` or `self`.
# Has no access to class or instance.
print("This is a regular method")
Accessing from Outside
Class attributes and methods can be accessed using either the class name or instance name.
The class name cannot be used to access instance member variables and methods.
class MyClass:
class_attribute = 0
@classmethod
def class_method(cls):
print("hello world")
# Access using class name.
print(MyClass.class_attribute)
MyClass.class_method()
# Access using instance name.
instance = MyClass()
print(instance.class_attribute)
instance.class_method()
Instance member variables and regular methods can be accessed only using the instance name. They cannot be accessed using the class name.
The values of class attributes will persist throughout the program, as instances of the class come and go. Instance member variables and methods live only within the instance.
Accessing from Inside
class MyClass:
# Class attribute
class_attribute = 140
# Instance variable
self.myvar1 = 0
# Instance constructor
def __init__(self):
self.myvar2 = 6
# Class method
@classmethod
def class_method(cls):
# Access class attribute
print(cls.class_attribute)
# Access instance variable
self.myvar1 = 2
# Check and get class attribute
if hasattr(MyClass, 'class_attribute'):
temp = getattr(MyClass, 'class_attribute')
setattr(MyClass, 'class_attribute', 17)
# Instance method
def print_vals(self):
# Access instance variables
print(self.myvar1, self.myvar2)
# Access class attribute
print(type(self).class_attribute)
# Set instance variable
setattr(self, 'myvar2', 43)
# Set class attribute
setattr(MyClass, 'class_attribute', 17)
# Static method
@staticmethod
def print_text(text_to_print: str):
print(text_to_print)