What is the class?
Class = a program-code-template that allows developers to create an object that has both variables (data) and behaviors (functions or methods).
object = state (attributes) + behavior (methods)
4 basic OOP concepts
EncapsulationAbstractionInheritancePolymorphismPython class coding tricks
class A:
class_attr = "a1"
def __init__(self):
self.a2 = "a2"
def check(self):
return self.class_attr
class B(A):
class_attr = "b1"
def __init__(self):
super().__init__()
b = B()
print(b.check())
# Result: b1class A:
def __init__(self):
self.__a = "Low"
self.b = "zyx"
def d(self):
print(self.__a, self.b)
class AA(A):
def __init__(self):
super().__init__()
self.__a = "Hihg"
self.b = "ijk"
aaa = AA()
aaa.d()
# Q: What will be printed in screen?
# Low adfclass A:
x = 2
class B(A): ...
class C(A): ...
def print_x():
print(A.x, B.x, C.x)
print_x()
B.x = 4
print_x()
A.x = 5
print_x()
# Q: What will be printed in screen?
# 2 2 2
# 2 4 2
# 5 4 5Best practices
- Set attributes in the constructor.
- Distinguish class-level and instance-level data and methods.
- Determine what is equal.
- Provide string representations.
- Know what is static.
- Decide what is internal and private.
- Set access to attributes.
- Use docstrings.