Skip to content

Commit 91151c2

Browse files
committed
__enter__
__getattr__ __next__
1 parent f7b107e commit 91151c2

File tree

3 files changed

+63
-0
lines changed

3 files changed

+63
-0
lines changed

class/example__enter__.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
class Conn:
2+
def __init__(self):
3+
print('Connecting...')
4+
5+
def __enter__(self):
6+
print('Connected to internet!')
7+
return self
8+
9+
def __exit__(self, exc_type, exc_val, exc_tb):
10+
print('Disconnected...')
11+
12+
13+
with Conn() as conn:
14+
print('Processing...')

class/example__getattr__.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
class Main:
2+
def __getattr__(self, attr):
3+
setattr(self, attr, "default")
4+
return attr
5+
6+
7+
class SeekAttr(Main):
8+
def __getattr__(self, attr):
9+
return super().__getattr__(attr)
10+
11+
12+
if __name__ == '__main__':
13+
master = Main()
14+
15+
master.name = "John"
16+
master.size = 100
17+
18+
print(master.name, master.size)
19+
20+
seek = SeekAttr()
21+
seek.name = "Maria"
22+
seek.size = 200
23+
24+
print(seek.name, seek.size)

class/example__next__.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
class Connection:
2+
__instance = None
3+
4+
def __new__(cls, *args, **kwargs):
5+
if cls.__instance is None:
6+
print('Connecting...')
7+
cls.__instance = super().__new__(cls)
8+
return cls.__instance
9+
else:
10+
print("Warning: There\'s already a connection!")
11+
return cls.__instance
12+
13+
def __init__(self):
14+
print('Connected to internet!')
15+
16+
def __del__(self):
17+
print('Disconnected...')
18+
19+
20+
connection = Connection()
21+
22+
connection2 = Connection()
23+
24+
connection3 = Connection()
25+

0 commit comments

Comments
 (0)