-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclass.py
More file actions
75 lines (63 loc) · 1.99 KB
/
class.py
File metadata and controls
75 lines (63 loc) · 1.99 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
63
64
65
66
67
68
69
70
71
72
73
74
75
# 클래스 사용하기
# Person 클래스 정의
class Person:
def greeting(self):
print('Hello')
# 파이썬에서 흔히 볼 수 있는 클래스
a = int(10)
print(a)
b = list(range(10))
print(b)
c = dict(x = 10, y = 20)
print(c)
# type 객체
a = 10
print(type(a))
b = [0, 1, 2]
print(type(b))
c = {'x': 10, 'y': 20}
print(type(c))
maria = Person()
print(type(maria))
# 메서드 안에서 메서드 호출하기
class Person:
def greeting(self):
print('Hello')
def hello(self):
self.greeting() # self.메서드() 형식으로 클래스 안의 메서드를 호출
james = Person()
james.hello() # Hello
# 속성 사용하기
class Person:
def __init__(self):
self.hello = '안녕하세요.'
def greeting(self):
print(self.hello)
james = Person()
james.greeting() # 안녕하세요.
# 인스턴스를 만들 때 값 받기
class Person:
def __init__(self, name, age, address):
self.hello = '안녕하세요.'
self.name = name
self.age = age
self.address = address
def greeting(self):
print('{0} 저는 {1} 입니다.'.format(self.hello, self.name))
maria = Person('마리아', 20, '서울시 서초구 반포동')
maria.greeting() # 안녕하세요. 저는 마리아입니다.
print('이름:', maria.name) # 마리아
print('나이:', maria.age) # 20
print('주소:', maria.address) # 서울시 서초구 반포동
# 비공개 속성 사용하기
class Person:
def __init__(self, name, age, address, wallet):
self.name = name
self.age = age
self.address = address
self.__wallet = wallet # 변수 앞에 __를 붙여서 비공개 속성으로 만듦
def pay(self, amount):
self.__wallet -= amount # 비공개 속성은 클래스 안의 메서드에서만 접근할 수 있음
print('이제 {0}원 남았네요.'.format(self.__wallet))
maria = Person('마리아', 20, '서울시 서초구 반포동', 10000)
maria.pay(3000)