728x90
10.파이썬 모듈¶
In [1]:
# 241 현재시간
import datetime
In [2]:
print(datetime.datetime.now())
2022-01-07 09:43:15.246189
In [3]:
# 242 현재시간의 타입
a=datetime.datetime.now()
print(a, type(a))
2022-01-07 09:43:15.262159 <class 'datetime.datetime'>
In [4]:
# 243 timedelta
a= datetime.datetime.now()
for i in range(5,0,-1):
delta = datetime.timedelta(days=i)
result= a-delta
print(result)
2022-01-02 09:43:15.279100
2022-01-03 09:43:15.279100
2022-01-04 09:43:15.279100
2022-01-05 09:43:15.279100
2022-01-06 09:43:15.279100
In [5]:
# 244 strftime
import datetime
now = datetime.datetime.now()
print(now.strftime("%H:%M:%S"))
09:43:15
In [6]:
# 245 strptime
import datetime
cal = "2020-05-04"
a = datetime.datetime.strptime(cal,"%Y-%m-%d")
print(a)
2020-05-04 00:00:00
In [7]:
# 246 sleep 함수
import time
import datetime
# 247 모듈 임포트
import 작성하기
In [8]:
# 248 os 모듈
import os
print(os.getcwd())
C:\sona\KDT\1wk
In [9]:
# 249 rename 함수
import os
os.rename( , )
File "C:\Users\Admin\AppData\Local\Temp/ipykernel_8464/2644935516.py", line 4
os.rename( , )
^
SyntaxError: invalid syntax
In [10]:
# 250 numpy
import numpy as np
In [11]:
import numpy
for i in numpy.arange(0, 5, 0.1):
print(i)
0.0
0.1
0.2
0.30000000000000004
0.4
0.5
0.6000000000000001
0.7000000000000001
0.8
0.9
1.0
1.1
1.2000000000000002
1.3
1.4000000000000001
1.5
1.6
1.7000000000000002
1.8
1.9000000000000001
2.0
2.1
2.2
2.3000000000000003
2.4000000000000004
2.5
2.6
2.7
2.8000000000000003
2.9000000000000004
3.0
3.1
3.2
3.3000000000000003
3.4000000000000004
3.5
3.6
3.7
3.8000000000000003
3.9000000000000004
4.0
4.1000000000000005
4.2
4.3
4.4
4.5
4.6000000000000005
4.7
4.800000000000001
4.9
11. 파이썬 클래스¶
In [12]:
# 251 클래스, 객체, 인스턴스
In [13]:
# 252 클래스 정의
class Human:
pass
In [14]:
# 253 인스턴스 생성
class Human:
pass
areum = Human()
In [15]:
# 254 클래스 생성자-1
class Human:
def __init__(self):
print("응야응애")
areum = Human()
응야응애
In [16]:
# 255 클래스 생성자-2
class Human:
def __init__(self,이름,나이,성별):
self.name = 이름
self.age = 나이
self.sex = 성별
In [17]:
areum = Human("아름",25,"여자")
In [18]:
# 확인하기
print(areum.name, areum.age, areum.sex)
아름 25 여자
In [19]:
# 256 인스턴스 속성에 접근
# 1) 인스턴스의 이름, 나이, 성별을 출력하세요.
# 2) 인스턴스 변수에 접근하여 값을 출력하면 됩니다.
class Human:
def __init__(self, name, age, sex):
self.name = name
self.age = age
self.sex = sex
areum = Human("조아름", 25, "여자")
In [20]:
# 1)
print("이름: {}, 나이: {}, 성별: {}".format(areum.name, areum.age, areum.sex))
# 2)
print(areum.age)
이름: 조아름, 나이: 25, 성별: 여자
25
In [21]:
# 257 클래스 메소드 - 1
class Human:
def __init__(self,name,age,sex):
self.name = name
self.age = age
self.sex = sex
def who(self):
print(("이름: {}, 나이: {}, 성별: {}").format(self.name,self.age,self.sex))
In [22]:
areum = Human("조아름",25,"여자")
areum.who()
이름: 조아름, 나이: 25, 성별: 여자
In [23]:
# 258 클래스 메소드 - 2
class Human:
def __init__(self,name,age,sex):
self.name = name
self.age = age
self.sex = sex
def who(self):
print(("이름: {}, 나이: {}, 성별: {}").format(self.name,self.age,self.sex))
def setInfo(self,name,age,sex):
self.name = name
self.age = age
self.sex = sex
In [24]:
areum = Human("모름", 0, "모름")
#확인하기
areum.who()
이름: 모름, 나이: 0, 성별: 모름
In [25]:
areum.setInfo("아름", 25, "여자")
# 확인하기
areum.who()
이름: 아름, 나이: 25, 성별: 여자
In [26]:
# 259 클래스 소멸자
class Human:
def __init__(self,name,age,sex):
self.name = name
self.age = age
self.sex = sex
def __del__(self):
print("나의 죽음을 알리지마라")
def who(self):
print(("이름: {}, 나이: {}, 성별: {}").format(self.name,self.age,self.sex))
def setinfo(self,name,age,sex):
self.name=name
self.age=age
self.sex=sex
In [27]:
areum = Human("아름", 25, "여자")
del areum
나의 죽음을 알리지마라
In [28]:
# 260 에러의 원인
class OMG :
def print() :
print("Oh my god")
In [29]:
myStock = OMG()
myStock.print() #print() 함수에 selt가 없어서! 오류생김
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_8464/2259937438.py in <module>
1 myStock = OMG()
----> 2 myStock.print() #print() 함수에 selt가 없어서! 오류생김
TypeError: print() takes 0 positional arguments but 1 was given
In [30]:
# 고쳐보기!!!!!!!!1
class OMG :
def print(self) :
print("Oh my god")
mystock = OMG()
mystock.print()
Oh my god
In [31]:
# 261 Stock 클래스 생성
class Stock:
pass
In [32]:
# 262 생성자
class Stock:
def __init__(self,name,code):
self.name = name
self.code = code
In [33]:
삼성 = Stock("삼성전자", "005930")
#확인하기
print(삼성.name, 삼성.code)
삼성전자 005930
In [34]:
# 263 메서드
# 객체에 종목명을 입력할 수 있는 set_name 메서드를 추가해보세요.
class Stock:
def __init__(self,name,code):
self.name = name
self.code = code
def set_name(self,name):
self.name = name
In [35]:
a = Stock(None, None)
a.set_name("삼성전자")
# Stock.set_name(a,"삼성전자")와 동일
In [36]:
# 확인하기
print(a.name)
삼성전자
In [37]:
# 264 메서드
# 객체에 종목코드를 입력할 수 있는 set_code 메서드를 추가해보세요.
# 263 메서드
# 객체에 종목명을 입력할 수 있는 set_name 메서드를 추가해보세요.
class Stock:
def __init__(self,name,code):
self.name = name
self.code = code
def set_name(self,name):
self.name = name
def set_code(self,code):
self.code = code
In [38]:
a = Stock(None, None)
a.set_code("005930")
#Stock.set_code(a,"005930")과 동일
In [39]:
# 확인하기
print(a.code)
005930
In [40]:
# 265 메서드
# 1) 종목명과 종목코드를 리턴하는 get_name, get_code 메서드를 추가하세요.
class Stock:
def __init__(self,name,code):
self.name = name
self.code = code
def set_name(self,name):
self.name = name
def set_code(self,code):
self.code = code
def get_name(self):
return self.name
def get_code(self):
return self.code
삼성 = Stock("삼성전자", "005930")
In [41]:
# 2) 해당 메서드를 사용하여 종목명과 종목코드를 얻고 이를 출력해보세요.
print(삼성.get_name())
print(삼성.get_code())
삼성전자
005930
In [42]:
# 266 객체의 속성값 업데이트
class Stock:
def __init__(self,name,code,per,pbr,dy):
self.name = name
self.code = code
self.per = per
self.pbr = pbr
self.dy = dy
def set_name(self,name):
self.name = name
def set_code(self,code):
self.code = code
def get_name(self):
return self.name
def get_code(self):
return self.code
In [43]:
# 267 객체 생성
삼성 = Stock("삼성전자", "005930", 15.79, 1.33, 2.83)
In [44]:
#확인용
print(삼성.per)
15.79
In [45]:
# 268 객체의 속성 수정
# PER, PBR, 배당수익률은 변경될 수 있는 값입니다.
# 이 값을 변경할 때 사용하는 set_per, set_pbr, set_dividend 메서드를 추가
class Stock:
def __init__(self, name, code, per, pbr, dividend):
self.name = name
self.code = code
self.per = per
self.pbr = pbr
self.dividend = dividend
def set_name(self, name):
self.name = name
def set_code(self, code):
self.code = code
def get_name(self):
return self.name
def get_code(self):
return self.code
def set_per(self, per):
self.per = per
def set_pbr(self, pbr):
self.pbr = pbr
def set_dividend(self, dividend):
self.dividend = dividend
In [46]:
# 269 객체의 속성 수정
# 267번에서 생성한 객체에 set_per 메서드를 호출하여 per 값을 12.75로 수정해보세요.
삼성 = Stock("삼성전자", "005930", 15.79, 1.33, 2.83)
print("현재는", 삼성.per) # 변경 전
현재는 15.79
In [47]:
삼성.set_per(12.75)
print("바뀐 값은", 삼성.per) # 변경 후
바뀐 값은 12.75
In [48]:
# 270 여러 종목의 객체 생성
# 1) 3종목에 대해 객체를 생성하고 이를 파이썬 리스트에 저장
삼성 = Stock("삼성전자", "005930", 15.79, 1.33, 2.83)
현대차 = Stock("현대차", "005380", 8.70, 0.35, 4.27)
LG전자 = Stock("LG전자", "066570", 317.34, 0.69, 1.37)
In [49]:
# 2) for 루프를 통해 종목코드와 PER을 출력
for i in [삼성,현대차,LG전자]:
print(i.code, i.per)
005930 15.79
005380 8.7
066570 317.34
In [55]:
# 271 Account 클래스
# 조건1) 예금주와 초기 잔액만 입력 받습니다.
# 조건2) 은행이름은 SC은행으로
# 조건3) 계좌번호는 3자리-2자리-6자리 형태로
# 조건4) 랜덤하게 생성
import random
a=random.randrange(0,1000)
b=random.randrange(0,100)
c=random.randrange(0,1000)
print(a,b,c)
211 62 333
In [130]:
# 나중에 3/2/6자리로 받아야함
aa = "%03d"%a #3자리 테스트
#확인하기
print(aa, type(aa))
211 <class 'str'>
In [70]:
class Account:
def __init__(self,name,balance): # 조건1) 예금주와 초기 잔액만 입력 받습니다.
self.name = name
self.balance = balance
self.bank = "SC은행" # 조건2) 은행이름은 SC은행으로
# 조건3) 계좌번호는 3자리-2자리-6자리 형태로
# 조건4) 랜덤하게 생성
# 3파트로 구분
first = random.randrange(0,1000)
second = random.randrange(0,100)
three = random.randrange(0,1000000) #6자리
#계좌번호 생성하기
self.account_num = "%03d"%first +"-" + "%02d"%second +"-"+ "%06d"%three
In [71]:
#잘 만들어졌나 확인하기!!!
#예금주와 초기잔액 확인
test = Account("소나",1000)
print(test.name, test.balance)
# 은행과 계좌번호 확인
print(test.bank, test.account_num)
소나 1000
SC은행 800-26-204
In [81]:
# 272 클래스 변수
# 클래스 변수를 사용해서 Account 클래스로부터 생성된 계좌 객체의 개수를 저장
class Account:
cnt = 0
def __init__(self,name,balance): # 조건1) 예금주와 초기 잔액만 입력 받습니다.
self.name = name
self.balance = balance
self.bank = "SC은행" # 조건2) 은행이름은 SC은행으로
# 조건3) 계좌번호는 3자리-2자리-6자리 형태로
# 조건4) 랜덤하게 생성
# 3파트로 구분
first = random.randrange(0,1000)
second = random.randrange(0,100)
three = random.randrange(0,1000000) #6자리
#계좌번호 생성하기
self.account_num = "%03d"%first +"-" + "%02d"%second +"-"+ "%06d"%three
Account.cnt+=1 #Account 클래스 사용해서
In [82]:
# 잘 만들어졌는지 확인해보기!!!
test1= Account("또방",1000)
test2= Account("꾸꾸",1000)
test3= Account("리꾸",1000)
print(Account.cnt)
3
In [86]:
# 273 클래스 변수 출력
# 생성된 계좌의 개수를 출력하는 get_account_num() 메서드를 추가하세요.
class Account:
cnt = 0
def __init__(self,name,balance): # 조건1) 예금주와 초기 잔액만 입력 받습니다.
self.name = name
self.balance = balance
self.bank = "SC은행" # 조건2) 은행이름은 SC은행으로
# 조건3) 계좌번호는 3자리-2자리-6자리 형태로
# 조건4) 랜덤하게 생성
# 3파트로 구분
first = random.randrange(0,1000)
second = random.randrange(0,100)
three = random.randrange(0,1000000) #6자리
#계좌번호 생성하기
self.account_num = "%03d"%first +"-" + "%02d"%second +"-"+ "%06d"%three
# 생성된 계좌 객체의 개수
Account.cnt+=1 #Account 클래스 사용해서
def get_account_num(self):
print(self.cnt)
In [87]:
# 잘 만들어졌는지 확인해보기!!!
test1= Account("또방",1000)
test2= Account("꾸꾸",1000)
test1.get_account_num()
2
In [105]:
# 274 입금 메서드
# 입금을 위한 deposit 메서드를 추가하세요. 입금은 최소 1원 이상만 가능합니다.
class Account:
cnt = 0
def __init__(self,name,balance): # 조건1) 예금주와 초기 잔액만 입력 받습니다.
self.name = name
self.balance = balance
self.bank = "SC은행" # 조건2) 은행이름은 SC은행으로
# 조건3) 계좌번호는 3자리-2자리-6자리 형태로
# 조건4) 랜덤하게 생성
# 3파트로 구분
first = random.randrange(0,1000)
second = random.randrange(0,100)
three = random.randrange(0,1000000) #6자리
#계좌번호 생성하기
self.account_num = "%03d"%first +"-" + "%02d"%second +"-"+ "%06d"%three
# 생성된 계좌 객체의 개수
Account.cnt+=1 #Account 클래스 사용해서
def get_account_num(x):
print(x.cnt)
def deposit(self,money): # 함수추가 <<<<==========================
# 입금은 최소 1원 이상만 가능합니다.
if money >= 1 :
self.balance +=money
In [103]:
# 잘 만들어졌는지 확인해보기!!!
test1= Account("또방",1000)
test1.deposit(500)
print(test1.balance)
1500
In [104]:
# 잘 만들어졌는지 확인해보기!!!
test2= Account("꾸꾸",1000)
test2.deposit(0)
print(test2.balance)
1000
In [114]:
# 275 출금 메서드
# Account 클래스에 출금을 위한 withdraw 메서드를 추가하세요.
class Account:
cnt = 0
def __init__(self,name,balance): # 조건1) 예금주와 초기 잔액만 입력 받습니다.
self.name = name
self.balance = balance
self.bank = "SC은행" # 조건2) 은행이름은 SC은행으로
# 조건3) 계좌번호는 3자리-2자리-6자리 형태로
# 조건4) 랜덤하게 생성
# 3파트로 구분
first = random.randrange(0,1000)
second = random.randrange(0,100)
three = random.randrange(0,1000000) #6자리
#계좌번호 생성하기
self.account_num = "%03d"%first +"-" + "%02d"%second +"-"+ "%06d"%three
# 생성된 계좌 객체의 개수
Account.cnt+=1 #Account 클래스 사용해서
def get_account_num(x):
print(x.cnt)
def deposit(self,money):
if money >= 1 :
self.balance +=money
def withdraw(self,money): # 함수추가 <<<<==========================
# 출금은 계좌의 잔고 이상으로 출금할 수는 없습니다.
if self.balance > money:
self.balance -= money
In [110]:
# 잘 만들어졌는지 확인해보기!!!
test1= Account("또방",1000) #잔액 1000
test1.deposit(500) #입금 +500
test1.withdraw(300) #출금 -300
print(test1.balance)
1200
In [115]:
# 잘 만들어졌는지 확인해보기!!!
test2= Account("꾸꾸",1000) #w잔액 1000
test2.withdraw(1500) #출금 -1500
# 예상답 : 출금이 진행되지 않아, 잔액그대로 출력
print(test2.balance)
1000
In [116]:
# 276 정보 출력 메서드
#Account 인스턴스에 저장된 정보를 출력하는 display_info() 메서드를 추가하세요.
# 조건) 잔고는 세자리마다 쉼표를 출력하세요.
print( '{0:,}'.format(100000000000) )
100,000,000,000
In [128]:
class Account:
cnt = 0
def __init__(self,name,balance): # 예금주와 초기 잔액만 입력 받습니다.
self.name = name
self.balance = balance
self.bank = "SC은행" # 은행이름은 SC은행으로
# 계좌번호는 3자리-2자리-6자리 형태로 랜덤하게 생성
first = random.randrange(0,1000) # 3자리
second = random.randrange(0,100) # 2자리
three = random.randrange(0,1000000) #6자리
#계좌번호 생성하기
self.account_num = "%03d"%first +"-" + "%02d"%second +"-"+ "%06d"%three
# 생성된 계좌 객체의 개수
Account.cnt+=1 #Account 클래스 사용해서
def get_account_num(x):
print(x.cnt)
def deposit(self,money):
# 입금은 최소 1원 이상만 가능합니다.
if money >= 1 :
self.balance +=money
def withdraw(self,money):
# 출금은 계좌의 잔고 이상으로 출금할 수는 없습니다.
if self.balance > money:
self.balance -= money
def display_info(self): # 함수추가 <<<<==========================
print("은행이름: {}".format(self.bank))
print("예금주: {}".format(self.name))
print("계좌번호: {}".format(self.account_num))
print("잔고: {0:,}원".format(self.balance))
In [129]:
p = Account("파이썬", 10000)
p.display_info()
은행이름: SC은행
예금주: 파이썬
계좌번호: 602-51-463562
잔고: 10,000원
In [ ]:
# 277 이자 지급하기
# 조건) 입금 횟수가 5회가 될 때,
# 잔고를 기준으로 1%의 이자가 잔고에 추가되도록 코드를 변경해보세요.
In [149]:
import random
class Account:
account_cnt = 0
def __init__(self,name,balance): # 예금주와 초기 잔액만 입력 받습니다.
#입금횟수 만들기 <<<<==========================
self.deposit_cnt = 0
self.name = name
self.balance = balance
self.bank = "SC은행" # 은행이름은 SC은행으로
# 계좌번호는 3자리-2자리-6자리 형태로 랜덤하게 생성
first = random.randrange(0,1000) # 3자리
second = random.randrange(0,100) # 2자리
three = random.randrange(0,1000000) #6자리
#계좌번호 생성하기
self.account_num = "%03d"%first +"-" + "%02d"%second +"-"+ "%06d"%three
# 생성된 계좌 객체의 개수
Account.account_cnt+=1 #Account 클래스 사용해서
def get_account_num(self):
print(self.account_cnt)
def deposit(self,money):
# 입금은 최소 1원 이상만 가능합니다.
if money >= 1 :
self.balance +=money
self.deposit_cnt +=1 # 입금 횟수 더하고 <<<<==========================
if self.deposit_cnt %5 ==0: #5회가 될때마다 (조건식) <<<<==========================
self.balance = (self.balance *1.01) #balance에서 이자 1% 추가해주기 <<<<==========================
def withdraw(self,money):
# 출금은 계좌의 잔고 이상으로 출금할 수는 없습니다.
if self.balance > money:
self.balance -= money
def display_info(self):
print("은행이름: {}".format(self.bank))
print("예금주: {}".format(self.name))
print("계좌번호: {}".format(self.account_num))
print("잔고: {0:,}원".format(self.balance))
In [150]:
# 확인해보기
test1= Account("또방",1000)
test1.deposit(1000) # +1000원
test1.deposit(1000) # +1000원
test1.deposit(1000) # +1000원
test1.deposit(1000) # +1000원
test1.deposit(1000) # +1000원
# --------------------원금의 합이 6천원
print(test1.balance)
6060.0
In [156]:
# 278 여러 객체 생성
a = Account("유재석",1000000)
b = Account("하하",10000)
c = Account("정준하",1000)
custom=[]
custom.append(a)
custom.append(b)
custom.append(c)
In [157]:
custom
Out[157]:
[<__main__.Account at 0x2a3d31aa5e0>,
<__main__.Account at 0x2a3d31aaa90>,
<__main__.Account at 0x2a3d31aa370>]
In [161]:
# 279 객체 순회
# 반복문을 통해 리스트에 있는 객체를 순회하면서
# 잔고가 100만원 이상인 고객의 정보만 출력하세요.
for i in custom:
if i.balance >= 1000000:
i.display_info()
은행이름: SC은행
예금주: 유재석
계좌번호: 031-96-422306
잔고: 1,000,000원
In [162]:
# 280 입출금 내역
# 입금과 출금 내역이 기록되도록 코드를 업데이트 하세요.
# 입금 내역 deposit_history과 출금 내역withdraw_history 출력 메서드를 추가
In [213]:
import random
class Account:
account_cnt = 0
def __init__(self,name,balance): # 예금주와 초기 잔액만 입력 받습니다.
self.deposit_cnt = 0 #입금횟수 만들기
self.deposit_mem = [] #입금 기록 <==============
self.withdraw_mem = [] #출금 기록 <============
self.name = name
self.balance = balance
self.bank = "SC은행" # 은행이름은 SC은행으로
# 계좌번호는 3자리-2자리-6자리 형태로 랜덤하게 생성
first = random.randrange(0,1000) # 3자리
second = random.randrange(0,100) # 2자리
three = random.randrange(0,1000000) #6자리
#계좌번호 생성하기
self.account_num = "%03d"%first +"-" + "%02d"%second +"-"+ "%06d"%three
# 생성된 계좌 객체의 개수
Account.account_cnt+=1 #Account 클래스 사용해서
def get_account_num(self):
print(self.account_cnt)
def deposit(self,money):
# 입금은 최소 1원 이상만 가능합니다.
if money >= 1 :
self.deposit_mem.append(money) #입금액추가<===========
self.balance +=money
self.deposit_cnt +=1 # 입금 횟수 더하고
#5회가 될때마다 (조건식) balance에서 이자 1% 추가해주기
if self.deposit_cnt %5 ==0:
self.balance = (self.balance *1.01)
def withdraw(self, money):
# 출금은 계좌의 잔고 이상으로 출금할 수는 없습니다.
if self.balance > money:
self.withdraw_mem.append(money) #출금액추가<===========
self.balance -= money
def display_info(self):
print("은행이름: {}".format(self.bank))
print("예금주: {}".format(self.name))
print("계좌번호: {}".format(self.account_num))
print("잔고: {0:,}원".format(self.balance))
def deposit_history(self):
for i in self.deposit_mem:
print("{}원이 입금 되었습니다.".format(i))
def withdraw_history(self):
for i in self.withdraw_mem:
print("{}원이 출금 되었습니다.".format(i))
In [214]:
#제대로 들어갔다 확인해보기!!!
test = Account ("또방", 1000)
In [215]:
test.deposit(2000)
test.deposit(3000)
test.deposit(4000)
test.deposit(5000)
test.deposit_history()
2000원이 입금 되었습니다.
3000원이 입금 되었습니다.
4000원이 입금 되었습니다.
5000원이 입금 되었습니다.
In [216]:
test.withdraw(10)
test.withdraw(20)
test.withdraw(30)
test.withdraw(40)
test.withdraw_history()
10원이 출금 되었습니다.
20원이 출금 되었습니다.
30원이 출금 되었습니다.
40원이 출금 되었습니다.
In [2]:
# 281 클래스 정의
# 다음 코드가 동작하도록 차 클래스를 정의하세요.
class 차:
def __init__(self,바퀴,가격):
self.바퀴 = 바퀴
self.가격 = 가격
In [5]:
car = 차(2, 1000)
car.바퀴
Out[5]:
2
In [6]:
car.가격
Out[6]:
1000
In [7]:
# 282 클래스 상속
class 차:
def __init__(self,바퀴,가격):
self.바퀴 = 바퀴
self.가격 = 가격
class 자전차(차):
pass
In [10]:
# 283 클래스 상속
class 차:
def __init__(self,바퀴,가격):
self.바퀴 = 바퀴
self.가격 = 가격
class 자전차(차):
def __init__(self, 바퀴, 가격):
self.바퀴 = 바퀴
self.가격 = 가격
In [11]:
bicycle = 자전차(2, 100)
bicycle.가격
Out[11]:
100
In [14]:
# 284 클래스 상속
class 차:
def __init__(self,바퀴,가격):
self.바퀴 = 바퀴
self.가격 = 가격
class 자전차(차):
def __init__(self, 바퀴, 가격, 구동계):
super().__init__(바퀴,가격)
self.구동계 = 구동계
In [16]:
bicycle = 자전차(2, 100, "시마노")
print(bicycle.구동계)
print(bicycle.바퀴)
시마노
2
In [18]:
# 285 클래스 상속
class 차:
def __init__(self,바퀴,가격):
self.바퀴 = 바퀴
self.가격 = 가격
class 자전차(차):
def __init__(self, 바퀴, 가격, 구동계):
super().__init__(바퀴,가격)
self.구동계 = 구동계
class 자동차(차):
def __init__(self, 바퀴, 가격):
super().__init__(바퀴,가격)
def 정보(self):
print("바퀴수",self.바퀴)
print("가격", self.가격)
In [19]:
car = 자동차(4, 1000)
car.정보()
바퀴수 4
가격 1000
In [20]:
# 286 부모 클래스 생성자 호출
class 차:
def __init__(self,바퀴,가격):
self.바퀴 = 바퀴
self.가격 = 가격
def 정보(self):
print("바퀴수",self.바퀴)
print("가격", self.가격)
class 자전차(차):
def __init__(self, 바퀴, 가격, 구동계):
super().__init__(바퀴,가격)
self.구동계 = 구동계
class 자동차(차):
def __init__(self, 바퀴, 가격):
super().__init__(바퀴,가격)
In [21]:
bicycle = 자전차(2, 100, "시마노")
bicycle.정보()
바퀴수 2
가격 100
In [25]:
# 287 부모 클래스 메서드 호출
class 차:
def __init__(self,바퀴,가격):
self.바퀴 = 바퀴
self.가격 = 가격
def 정보(self):
print("바퀴수",self.바퀴)
print("가격", self.가격)
class 자전차(차):
def __init__(self, 바퀴, 가격, 구동계):
super().__init__(바퀴,가격)
self.구동계 = 구동계
def 정보(self):
super().정보()
print("구동계",self.구동계)
class 자동차(차):
def __init__(self, 바퀴, 가격):
super().__init__(바퀴,가격)
In [26]:
bicycle = 자전차(2, 100, "시마노")
bicycle.정보()
바퀴수 2
가격 100
구동계 시마노
In [27]:
# 288 메서드 오버라이딩
class 부모:
def 호출(self):
print("부모호출")
class 자식(부모):
def 호출(self):
print("자식호출")
나 = 자식()
나.호출()
#자식클래스에 호출()있으니 우선순위 1번 만약, 자식클래스에 없었다면 부모클래스의 호출()가 실행되어 "부모생성"이 나왔을것이다.
자식호출
In [28]:
# 289 생성자
class 부모:
def __init__(self):
print("부모생성")
class 자식(부모):
def __init__(self):
print("자식생성")
나 = 자식()
# 자식 클래스 생성자 실행됨
자식생성
In [29]:
# 290 부모클래스 생성자 호출
class 부모:
def __init__(self):
print("부모생성")
class 자식(부모):
def __init__(self):
print("자식생성")
super().__init__()
나 = 자식()
# 먼저 자식클래스의 생성자안 출력 됨
# 그래서 자식생성 출력 & 상속받은 부모클래스도 출력
자식생성
부모생성
728x90
'😁 빅데이터 문제 풀기 & Study > - 이외 사이트 문제' 카테고리의 다른 글
[Pandas] Pandas 연습 문제 풀기 - 2 🐼 (0) | 2022.02.21 |
---|---|
[Pandas] Pandas 연습 문제 풀기 - 1 🐼 (0) | 2022.02.21 |
초보자를 위한 파이썬 300제 (290~300번) 12. 파일 입출력과 예외처리 (0) | 2022.01.07 |
초보자를 위한 파이썬 300제 (201~240번) 9. 파이썬 함수 (0) | 2022.01.07 |
초보자를 위한 파이썬 300제 (131~200번) 8. 파이썬 반복문 (0) | 2022.01.07 |