class MyClass:
def __init__(self, name):
self.name = name
self.data = []
def do_something(self, x):
self.data.append(x)
myObject = MyClass("bob")
Or optionally with type hints:
myObject: MyClass = MyClass("bob")
class MyClass:
"""
Documentation of class
"""
def do_something(self, x):
"""Documentation of method"""
self.data.append(x)
Need to use decorators for classmethod and staticmethod to get them to work properly, though possibly being phased out?
class MyClass:
x = 1
def __init__(self, name):
self.name = name
self.data = []
@classmethod
def do_something(cls, y):
cls.x = y
class MyClass:
@staticmethod
def do_something(x):
print(x)
Can be used to validate data, present properly and ensure encapsulation.
__getaddr__
__setaddr__
__deladdr__
Called when object deleted (eg by garbage collector or "del myObject")
class MyClass:
def __init__(self, name):
self.name = name
self.data = []
def __del__(self):
pass
class MyClass:
def __init__(self, things):
self.things = things
def __len__(self):
return len(self.things)
Can overload other operators too.
class MyClass:
def __init__(self, val):
self.val = val
def __add__(self, other):
return len(self.val + other.val)
x = MyClass(1)
y = MyClass(2)
x + y
__iter__
__next__
class BaseClass:
x = 1
class DerivedClass(BaseClass):
y = 1
issubclass(class, classinfo)
Public: Accessible from anywhere Protected: Accessible from within class and subclass Private: Accessible from within class
Done with underscores. \(x\) below is public. \(y\) is protected. \(z\) is private.
class MyClass:
def __init__(self, x, y, z):
self.x = x
self._y = y
self.__z = z
Can also do these for methods
class MyClass:
def a():
print(1)
def _b():
print(2)
def __c()
print(3)
Used for encapsulation and cleaning.
class MyClass:
def __init__(self, x, y, z):
self.x = x
self._y = y
self.__z = z
def get_z(self):
return(self.__z)
def set_y(self, y):
self._y = y
class BaseClassA:
x = 1
class BaseClassB:
y = 1
class DerivedClass(BaseClassA, BaseClassB):
z = 1
Access methods and parameters from parent class.
class BaseClass:
x = 1
class DerivedClass(BaseClassA):
z = super().x + 1
class BaseClass:
def do_thing(self):
print(1)
class DerivedClass(BaseClassA):
def do_thing(self):
print(2)
Check is member of class or subclass.
isinstance(object, int)