Repository navigation
Expand file tree
/
Copy pathclassEx2.py
More file actions
62 lines (46 loc) · 1.96 KB
/
Copy pathclassEx2.py
File metadata and controls
62 lines (46 loc) · 1.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# 클래스 변수 vs 인스턴스 변수, 그리고 메서드의 종류
class Counter:
count = 0 # 클래스 변수 — 모든 객체가 함께 쓴다
def __init__(self, name):
self.name = name # 인스턴스 변수 — 객체마다 따로 가진다
Counter.count += 1 # 객체가 만들어질 때마다 하나씩 증가
a = Counter('첫번째')
b = Counter('두번째')
c = Counter('세번째')
print(a.name, b.name, c.name) # 각자 다르다
print('만들어진 개수 :', Counter.count) # 3 — 모두가 공유
print(a.count, b.count, c.count) # 전부 3
print('---------- 은닉 관례 : 밑줄 ----------')
class Account:
def __init__(self, owner, balance=0):
self.owner = owner
self._balance = balance # 밑줄 하나 = "밖에서 직접 건드리지 마세요" 관례
def deposit(self, amount):
if amount <= 0:
print('입금액은 0보다 커야 합니다')
return
self._balance += amount
def withdraw(self, amount):
if amount > self._balance:
print('잔액이 부족합니다')
return
self._balance -= amount
def get_balance(self):
return self._balance
acc = Account('홍길동', 1000)
acc.deposit(500)
acc.withdraw(2000) # 거부된다
acc.withdraw(300)
print(acc.owner, acc.get_balance())
# 밑줄은 강제가 아니라 약속입니다. acc._balance = 999999 라고 쓰면 됩니다.
# 하지만 그러면 deposit/withdraw 의 검사를 통째로 건너뛰게 됩니다.
# "왜 메서드를 통해서만 바꿔야 하는가"가 여기 있습니다.
print('---------- property : 메서드를 속성처럼 ----------')
class Circle:
def __init__(self, r):
self.r = r
@property
def area(self): # 괄호 없이 쓸 수 있다
return 3.14159 * self.r ** 2
c = Circle(5)
print(f'넓이 : {c.area:.2f}') # c.area() 가 아니라 c.area