python classes
class A:
def __init__(self, attr):
self.attr = attr
a = A(5)
print(a.attr)
# 5
class A:
common = 42
def __init__(self, attr):
self.attr = attr
a, b = A(5), A(6)
print(a.attr, b.attr)
# 5, 6
print(a.common, b.common)
# 42, 42
print(A.common)
# 42
# 0, 100, 100class A:
common = 42
def __init__(self, attr):
self.attr = attr
a.common = 0
print(a.common, b.common, A.common)
a, b = A(5), A(6)
A.common = 100
print(a.common, b.common, A.common)
# 100, 100, 100print(b.__dict__){'attr': 6}print(a.__dict__){'attr': 5, 'common': 0}for k, v in A.__dict__.items():
print(k, v)__module__ __main__
common 100
__init__ <function A.__init__ at 0x7fa8a8c4fd30>
__dict__ <attribute '__dict__' of 'A' objects>
__weakref__ <attribute '__weakref__' of 'A' objects>
__doc__ None# ищем 'attr' в __dict__ инстанса `a`
# ищем 'attr' в __dict__ класса `А`
class A:
def __init__(self, attr):
self.attr = attr
a = A(5)
print(a.attr)Traceback (most recent call last):
...
AttributeError: 'A' object has no attribute 'lol'class A:
pass
print(A().lol)class A:
pass
a = A()
print(a.__dict__)
# {}
print(a.lol)# 42print(a.__dict__){'lol': 42}a.lol = 42class A:
common = []
a, b = A(), A()
print(a.common, b.common, A.common)
# [], [], []
a.common.append('kek')
print(a.common, b.common, A.common)
# ['kek'] ['kek'] ['kek']class Student:
def __init__(self):
self.failed_tests = []
self.is_active = True
s = Student()
s.failed_tests.append('ИН ЯЗ')
s.failed_tests.append('ООП')
print(s.is_active) # True
s.failed_tests.append('Сети')
print(s.is_active) # True
class Student:
def __init__(self):
self.failed_tests = []
self.is_active = True
def add_failed_test(self, test):
self.failed_tests.append(test)
if len(self.failed_tests) >= 3:
self.is_active = Falseclass Student:
EXPEL_THRESHOLD = 3
def __init__(self):
self._failed_tests = []
self.is_active = True
def add_failed_test(self, test):
self._failed_tests.append(test)
if len(self._failed_tests) >= self.EXPEL_THRESHOLD:
self.is_active = Falses = Student()
s.add_failed_test('ИН ЯЗ')
s.add_failed_test('ООП')
print(s.is_active) # True
s.add_failed_test('Сети')
print(s.is_active) # False
while True:
try:
log_line = input()
except EOFError:
break
if not log_line:
break
... # обрабатываем строку лога
05 python classes
By persi
05 python classes
- 208