Here, __init__, __repr__, and __eq__ come for free.
from dataclasses import dataclass@dataclassclass Person: first_name: str# becomes a field last_name # no annotation → ignored by dataclasses id_number: str# becomes a fieldp = Person("John", "Smith", "509")
---------------------------------------------------------------------------NameError Traceback (most recent call last)
Input In [54], in <cell line: 3>() 1fromdataclassesimport dataclass
3@dataclass----> 4classPerson:
5 first_name: str# becomes a field 6 last_name # no annotation → ignored by dataclasses
Input In [54], in Person() 3@dataclass 4classPerson:
5 first_name: str# becomes a field----> 6last_name# no annotation → ignored by dataclasses 7 id_number: strNameError: name 'last_name' is not defined
Default values
datetime.date(2025, 6, 20)
from dataclasses import dataclass, fieldfrom datetime import date@dataclassclass Person: first_name: str last_name: str id_number: str email: str="չունի"# simple default signup_date: date = field(default_factory=date.today) # today by default lst: list= field(default_factory=list) # empty list by default# Usagep = Person("John", "Smith", "509")print(p.email, p.signup_date, p.lst)
@dataclass(frozen=True)class Person: first_name: str last_name: str id_number: str# Usagep = Person("John", "Smith", "509")p.first_name ="johnny la gente esta muy loca"# FrozenInstanceError
---------------------------------------------------------------------------FrozenInstanceError Traceback (most recent call last)
Input In [69], in <cell line: 10>() 7# Usage 8 p = Person("John", "Smith", "509")
---> 10p.first_name="johnny la gente esta muy loca"# FrozenInstanceError
File <string>:4, in __setattr__(self, name, value)FrozenInstanceError: cannot assign to field 'first_name'
Լավ նյութեր 1. https://realpython.com/introduction-to-python-generators/ 2. https://www.youtube.com/watch?v=bD05uGo_sVI
print(type(range(1,3)))print(range(1,3))
<class 'range'>
range(1, 3)
a = [i**2for i inrange(-3, 3)]print(a)a = {i**2for i inrange(-3, 3)}print(a)a = (i**2for i inrange(-3, 3))print(a)a =tuple(i**2for i inrange(-3, 3))print(a)
---------------------------------------------------------------------------TypeError Traceback (most recent call last)
Input In [108], in <cell line: 1>()----> 1for i in a:
2print(i)
TypeError: iter() returned non-iterator of type 'NoneType'
class VrazList:def__init__(self, lst):self.lst = lstself.index =0def__iter__(self):returnselfdef__next__(self): current =self.lst[self.index]self.index +=2return current
for i in [1, 2, 3, 4, 5]:print(i)
1
2
3
4
5
a = VrazList([1,2,3,4,5])# a_iter = iter(a)# next(a_iter)print(type(a))for i in a:print(i)# a -> iter(a)# next(a)# next(a)# while StopIteration:
<class '__main__.VrazList'>
1
3
5
---------------------------------------------------------------------------IndexError Traceback (most recent call last)
Input In [110], in <cell line: 7>() 3# a_iter = iter(a) 4# next(a_iter) 5print(type(a))
----> 7for i in a:
8print(i)
Input In [109], in VrazList.__next__(self) 9def__next__(self):
---> 10 current =self.lst[self.index] 11self.index +=2 12return current
IndexError: list index out of range
class VrazList:def__init__(self, lst):self.lst = lstself.index =0def__iter__(self):returnselfdef__next__(self):ifself.index >=len(self.lst):raiseStopIteration current =self.lst[self.index]self.index +=2return current
a = VrazList([1,2,3,4,5])for i in a:print(i)
1
3
5
a = VrazList([1,2,3,4,5])
whileTrue:try: i =next(a)print(i)exceptStopIteration:break
1
3
5
Context managers (with)
լավ նյութ՝ https://www.youtube.com/watch?v=-aKFBoZpiqA
f =open("panir.txt", "w")f.write("պանիր պանիր պանիր")print(f.closed) # Falsef.close()print(f.closed) # True
False
True
withopen("panir.txt", "w") as f: f.write("պանիր պանիր պանիր")# f.__exit__(None, None, None) # f.close() is called automaticallyprint(f.closed)# ոնցա՞ հասկանում որ պետքա close անի վերջում
True
Իրականում մենք ճկունություն ունենք ոչ միայն ընդգծելու թե ինչ պետք ա աշխատեի էդ f.write("պանիր պանիր պանիր")-ից հետո (էս դեպքում՝ f.close()), բայց նաև ինչ աշխատի մինչև էդ with-ի մեջ եղած կոդը
class Bacich:def__init__(self, name, mode):self.name = nameself.mode = modedef__enter__(self):print(f"\nհեսա փորձելու ենք բացել {self.name}-ը {self.mode} նպատակով")self.file=open(self.name, self.mode)returnself.filedef__exit__(self, exc_type, exc_val, traceback):print("\nփակենք")self.file.close()
with Bacich("panir.txt", "r") as f:# some codeprint(f.read())# print(f.closed)# # Bacich("panir.txt", "r") -> __enter__()# enter's returns -> f# print(f.read())# f.__exit__(None, None, None) # __exit__ is called automatically# f = Bacich("panir.txt", "r").__enter__()# # some code# Bacich("panir.txt", "r").__exit__()
հեսա փորձելու ենք բացել panir.txt-ը r նպատակով
պանիր պանիր պանիր
փակենք
f.closed
True
աշխատեց enter-ը հետո with-ի մեջի կոդը, հետո exit-ը
with Bacich("panir.txt", "r") as f:print("ա")print(f.read())print(f.closed)
հեսա փորձելու ենք բացել {self.name}ը {self.mode} նպատակով
ա
պանիր պանիր պանիր
փակենք
exc_type = None
exc_val = None
traceback = None
True
with Bacich("panir.txt", "r") as f:print("ա")print(lav_katakner_haykic)print(f.read())# ...# f.__exit__(Errort, ...., traceback)
հեսա փորձելու ենք բացել {self.name}ը {self.mode} նպատակով
ա
փակենք
exc_type = <class 'NameError'>
exc_val = name 'lav_katakner_haykic' is not defined
traceback = <traceback object at 0x0000023A1873C180>
---------------------------------------------------------------------------NameError Traceback (most recent call last)
Input In [134], in <cell line: 1>() 1with Bacich("panir.txt", "r") as f:
2print("ա")
----> 3print(lav_katakner_haykic)
4print(f.read())
NameError: name 'lav_katakner_haykic' is not defined
ԻՆչ-որ հարցրեք - հլը մի րոպե բայց, բայց open-ը ֆունցկիա ա ոչ թե class, էս ո՞նց ա աշխատում
with bacich("panir.txt", "r") as f:print("a")print(f.read())print(f.closed)
հեսա փորձելու ենք բացել panir.txtը r նպատակով
a
պանիր պանիր պանիր
ժամանակն է փակելու ֆայլը
True
Աշխատումա բացիչ ֆունկցիայի բոլոր տողերը մինչև yield
yield արած արժեքը վերագրվումա fին
աշխատումա withի միջի կոդը
աշխատումա yieldից հետո գրվածը
with bacich("panir.txt", "r") as f:print("a")print(lav_katakner_haykic_2)print(f.read())
---------------------------------------------------------------------------NameError Traceback (most recent call last)
Input In [45], in <cell line: 1>()----> 1withbacich("panir.txt", "r") as f:
2print("a")
3print(lav_katakner_haykic_2)
NameError: name 'bacich' is not defined
f.closed
True
from contextlib import contextmanager@contextmanagerdef bacich(name, mode):try:print(f"հեսա փորձելու ենք բացել {name}ը {mode} նպատակով\n")file=open(name, mode)yieldfilefinally: # որ միշտ աշխատիprint("\nժամանակն է փակելու ֆայլը")file.close()
with bacich("panir.txt", "r") as f:print("a")print(lav_katakner_haykic_2)print(f.read())
հեսա փորձելու ենք բացել panir.txtը r նպատակով
a
ժամանակն է փակելու ֆայլը
---------------------------------------------------------------------------NameError Traceback (most recent call last)
Input In [139], in <cell line: 1>() 1with bacich("panir.txt", "r") as f:
2print("a")
----> 3print(lav_katakner_haykic_2)
4print(f.read())
NameError: name 'lav_katakner_haykic_2' is not defined