Python - class,상속

2020. 9. 2. 20:15Python

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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
# test6.py
# 클래스
 
# class 클래스명:
#       멤버변수
#       메서드
 
# 클래스 정의
class Simple:
    pass
 
 
# 클래스 사용 -> 객체생성
= Simple()
 
 
# 클래스 정의 Service 클래스 이름
# 변수 a=10
# 함수 prn(self) "함수정의" 출력
# 함수 sum2(self,a,b) 두수받아서 두수합 리턴
class Service:
    a = 10
 
    def prn(self):
        print("함수정의")
 
    def sum2(self, a, b):
        return a + b
 
    pass
 
 
# 객체생성
#  멤버변수, 메서드 호출
= Service()
print(s.a)
s.prn()
print(s.sum2(12))
 
 
# 클래스 정의 Shape
# 멤버 함수  CircleArea(r) return 원의면적
# 멤버함수 RectangleArea(w,h) 사각형의 면적구해서 리턴
class Shape:
    def CircleArea(self, r):
        return 3.14 * (r ** 2)
 
    def RectangleArea(self, w, h):
        return w * h
 
    pass
 
 
# 객체생성
# CircleArea 메서드 호출 반지름 10
# RectangleArea 메서드 호출 너비 10 높이 20
= Shape()
print(s.CircleArea(10))
print(s.RectangleArea(1020))
 
 
# 초기값 설정 함수
class Person:
 
    def __init__(self, name, age):
        # 인스턴스 변수 self.name
        self.name = name
        self.age = age
 
    def intro(self):
        print("이름"self.name, "나이"self.age)
 
 
# 객체생성
# TypeError: __init__() missing 2 required positional arguments: 'name' and 'age'
= Person("홍길동"20)
p.intro()
 
 
# 클래스 FourCal 초기값 a,b 받아서 self.a  self.b  변수 설정 저장
# sum() 두수 합구해서 리턴
# sub() 두수 차구해서 리턴
# mul() 두수 곱구해서 리턴
# div() 두수 나눗셈해서 리턴
class FourCal:
    def __init__(self, a, b):
        self.a = a
        self.b = b
 
    def sum(self):
        return self.a + self.b
 
    def sub(self):
        return self.a - self.b
 
    def mul(self):
        return self.a * self.b
 
    def div(self):
        return int(self.a / self.b)
 
 
# 객체생성
# 메서드 호출
= FourCal(2010)
print(f.sum())
print(f.sub())
print(f.mul())
print(f.div())
 
 
# 클래스 상속
class Parent:
    def parent_prn(self):
        print("부모클래스 prn() 함수")
 
 
class Child(Parent):  # Parent 클래스 상속
    def child_prn(self):
        print("자식클래스 prn() 함수")
 
    # 메서드 오버라이딩 : 부모함수 재정의
    def parent_prn(self):
        print("자식클래스가 재정의한 부모클래스 prn() 함수")
 
 
= Child()
c.child_prn()
c.parent_prn()
 
 
# 부모클래스 Bicycle
# 초기값 color -> self.color 저장
# move(speed) 메서드 정의 speed 받아서 출력 color 자전거 시속 speed 킬로 전진
# stop() 메서드 정의 출력 color 자전거 정지
class Bicycle:
    def __init__(self, color):
        self.color = color
 
    def move(self, speed):
        print("%s 자전거 시속 %d 킬로 전진" % (self.color, speed))
 
    def stop(self):
        print(self.color, "자전거 정지")
 
 
# 자식클래스 FoldBicycle  상속 Bicycle
# fold() 메서드 정의 출력 color 자전거 접기
# stop() 메서드 오버라이딩 출력 color 폴더 자전거 정지
class FoldBicycle(Bicycle):
    def __init__(self, color):
        self.color = color
 
    def fold(self):
        print(self.color, "자전거 접기")
 
    def stop(self):
        # 부모의 메서드 호출
        super().stop()
        print(self.color, "폴더 자전거 정지")
 
 
# FoldBicycle 객체생성 move(speed) fold()  stop() 메서드 호출
= FoldBicycle("파란색")
f.move(30)
f.fold()
f.stop()
 
 
# __add__       __sub__
# 부모클래스 HousePark
# 멤버변수 lastname="박"
# 초기값 name 받아서 self.fullname 변수 <=self.lastname+name
# 메서드 travel(where)  출력  fullname 이 where 여행가다
 
class HousePark:
    lastname = "박"
 
    def __init__(self, name):
        self.fullname = self.lastname + name
 
    def travel(self, where):
        print(self.fullname, "이", where, "로 여행가다")
 
    #     부모 + 자식 __add__ 호출
    def __add__(self, other):
        print(self.fullname, "와", other.fullname, "여행지에서 만나다")
 
    #     부모 - 자식 __sub__ 호출
    def __sub__(self, other):
        print(self.fullname, "와", other.fullname, "여행지에서 헤어졌다.")
 
 
= HousePark("서준")
p.travel("로마")
 
 
# 자식클래스 HouseKim   상속 HousePark
# 멤버변수 lastname="김"
# travel(where,day) 메서드 오버라이딩  출력 fullname  where에 day일 여행가다
class HouseKim(HousePark):
    lastname = "김"
 
    def travel(self, where, day):
        print(self.fullname, where, "에", day, "일 여행가다")
 
 
= HouseKim("두한")
k.travel("종로"20)
# __add__ 호출
+ k
# __sub__ 호출
- k
 
 
# 다중상속
# 부모클래스 Tiger  jump() 메서드정의 출력 "호랑이점프"
# 부모클래스 Lion bite() 메서드 정의 출력 "사자꿀꺽"
# 자식클래스 Liger (Tiger,Lion) 다중상속
#   play() 메서드 정의 출력 "라이거 놀기"
#   jump() 메서드 오버라이딩 출력 "라이거 점프"
class Tiger:
    def jump(self):
        print("호랑이점프")
 
 
class Lion:
    def bite(self):
        print("사자꿀꺽")
 
 
class Liger(Tiger, Lion):
    def play(self):
        print("라이거 놀기")
 
    def jump(self):
        print("라이거 점프")
 
 
# Liger 객체생성   jump()  play()  bite()  메서드 호출
= Liger()
l.jump()
l.play()
l.bite()
 
 
# 클래스변수, 함수
# 객체생성 후 사용 인스턴스 변수 self.변수, 인스턴스 함수 함수(self)
# 객체 생성 없이 사용할수있는 클래스 변수, 클래스 함수
 
# 클래스 car
# 변수 count=0
# 초기값 설정 color 를 받아서 self.color 변수에 저장
# move 함수 출력 self.color차가 움직인다
class car:
    # 클래스 변수 : 클래스 정의시 기억장소 확보, 객체생성없이 사용가능
    # 객체생성했을때 클래스 변수 공통으로 사용가능
    count = 0
 
    def __init__(self, color):
        self.color = color
        car.count = car.count + 1
 
    def move(self):
        print(self.color, "차가 움직인다")
 
    # 클래스 함수 객체 생성없이 클래스에서 바로호출 self.color 사용못함
    @classmethod
    def check(cls, code):
        print(car.count, code)
 
    @staticmethod
    def check2():
        print(car.count, "static 정적 함수")
 
 
car.check("전기차")  # 0 전기차
car.check2()
print(car.count)
= car("빨강")
c.move()
car.check("수소차")  # 1 수소차
car.check2()
print(c.count)
c2 = car("파랑")
c2.move()
car.check("하이브리드")  # 2 하이브리드
car.check2()
print(c2.count)
 
cs

 

class와 class의 상속과 메서드 오버 로딩을 배워보았는데 문법이 확실히 엄청 쉬워서 그런지

금방 배워졌다. class 클래스명(상속할 클래스명): 으로 간단하게 상속이 되었고

자바에서는 불가능했던 다중 상속도 가능해서 파이썬이 왜 인기가 많은지 알게 되었다.

def __init__으로 생성자를 생성 가능하고 특이해서 그런지 확실히 잊어버리진 않을 것 같았고,

@classmethod, @staticmethod로 선언을 해주면 자바의 static  태그처럼 클래스 명만으로 호출이 가능한 기능도 있었다. 그 외에도 __add__, __sub__으로 클래스들을 가지고 바로 사용 가능한 신기한 함수도 있었다. 

__add__와 __sub__ 은 적용 가능한 기준이 1번과 2번을 더하겠다 하면 왼쪽 기준으로 적용이 가능한 개념이어서

1번 클래스에서만 정의가 가능하고 2번 클래스에서는 정의가 불가능했다.

처음에 자식 클래스에서 적용하려고 했는데 안되어서 물어보니 왼쪽 기준으로 적용을 할 수 있다고 해서 

좀 더 확실히 개념이 이해가 되었다.

'Python' 카테고리의 다른 글

Python - 파일 입출력, print(),input()  (0) 2020.09.02
Python - Exception  (0) 2020.09.02
Python - def(함수),lambda(람다함수)  (0) 2020.09.02
Python - for문,while 문  (0) 2020.08.21
Python - 리스트,배열  (0) 2020.08.21