Python 공부 기록-4

김시헌·2025년 3월 27일

사람 (Human) 클래스에 (이름, 나이, 성별)을 받는 생성자를 추가하세요.

코드

areum = Human("아름", 25, "여자")

위에서 생성한 인스턴스의 이름, 나이, 성별을 출력하세요. 인스턴스 변수에 접근하여 값을 출력하면 됩니다.

코드

class Human:
  def __init__(self,name,age,sex):
    self.name = name
    self.age = age
    self.sex = sex

areum = Human("아름", 25, "여자")
areum.age

실행 결과
25

사람 (Human) 클래스에서 이름, 나이, 성별을 출력하는 who() 메소드를 추가하세요.

코드

class Human:
  def __init__(self,name,age,sex):
    self.name = name
    self.age = age
    self.sex = sex
  
  def who(self):
    print(f"이름: {self.name}, 나이: {self.age}, 성별: {self.sex}")

areum = Human("조아름", 25, "여자")
areum.who()

실행 결과
이름: 조아름, 나이: 25, 성별: 여자

사람 (Human) 클래스에 (이름, 나이, 성별)을 받는 setinfo 매소드를 추가하세요.

코드

class Human:
  def __init__(self,name,age,sex):
    self.name = name
    self.age = age
    self.sex = sex

  def who(self):
    print(f"이름: {self.name}, 나이: {self.age}, 성별: {self.sex}")

  def setInfo(self,name,age,sex):
    self.name = name
    self.age = age
    self.sex = sex

aruem = Human("불명", "미상", "모름")
aruem.who()

aruem.setInfo("아름", 25, "여자")
aruem.who()

실행 결과
이름: 불명, 나이: 미상, 성별: 모름
이름: 아름, 나이: 25, 성별: 여자

사람 (Human) 클래스에 "나의 죽음을 알리지 말라"를 출력하는 소멸자를 추가하세요.

코드

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(f"이름: {self.name}, 나이: {self.age}, 성별: {self.sex}")

  def setInfo(self,name,age,sex):
    self.name = name
    self.age = age
    self.sex = sex

aruem = Human("불명", "미상", "모름")
aruem.who()

aruem.setInfo("아름", 25, "여자")
aruem.who()

del aruem

실행 결과
이름: 불명, 나이: 미상, 성별: 모름
이름: 아름, 나이: 25, 성별: 여자
나의 죽음을 알리지 말라

주식 종목에 대한 정보를 저장하는 Stock 클래스를 정의해보세요. 클래스는 속성과 매서드를 갖고 있지 않습니다.

코드

class Stock:
    pass

Stock 클래스의 객체가 생성될 때 종목명과 종목코드를 입력 받을 수 있도록 생성자를 정의해보세요.

코드

class Stock:
  def __init__(self,name,num):
    self.name = name
    self.num = num
삼성전자 = Stock("삼성전자", "005930")
print(삼성전자.name)
print(삼성전자.num)

실행 결과
삼성전자
005930

객체에 종목명을 입력할 수 있는 set_name 메서드를 추가해보세요.

코드

class Stock:
  def __init__(self,name,num):
    self.name = name
    self.num = num
  def set_name(self,name):
    self.name = name

삼성전자 = Stock("삼성전자", "005930")
print(삼성전자.name)
print(삼성전자.num)

a = Stock(None, None)
a.set_name("삼성전자")
a.name

실행 결과
삼성전자
005930
'삼성전자'

객체에 종목코드를 입력할 수 있는 set_code 매서드를 추가해보세요.

코드

class Stock:
  def __init__(self,name,num):
    self.name = name
    self.num = num
  def set_name(self,name):
    self.name = name
  def set_code(self,code):
    self.code = code

삼성전자 = Stock("삼성전자", "005930")
print(삼성전자.name)
print(삼성전자.num)

a = Stock(None, None)
a.set_name("삼성전자")
a.name

a = Stock(None, None)
a.set_code("005930")
a.code

실행 결과
삼성전자
005930
'005930'

종목명과 종목코드를 리턴하는 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")
print(삼성.name)
print(삼성.code)
print(삼성.get_name())
print(삼성.get_code())

실행 결과
삼성전자
005930
삼성전자
005930

생성자에서 종목명, 종목코드, PER, PBR, 배당수익률을 입력 받을 수 있도록 생성자를 수정하세요. PER, PBR 배당수익률은 float 타입입니다.

코드

class Stock:
  def __init__(self,name,code):
    self.name = name
    self.code = code
    self.per = per
    self.pbr = pbr
    self.배당수익률 = 배당수익률

  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

위에서 정의한 생성자를 통해 다음 정보를 갖는 객체를 생성해보세요.

항목 / 정보
종목명 / 삼성전자
종목코드 / 005930
PER / 15.79
PBR / 1.33
배당수익률 / 2.83

코드

삼성 = Stock("삼성전자, "005930", 15.79, 1.33, 2.83)
print(삼성.배당수익률)

PER, PBR, 배당수익률은 변경될 수 있는 값입니다. 이 값을 변경할 때 사용하는 set_per, set_pbr, set_dividend 매서드를 추가하세요.

코드

class Stock:
  def __init__(self,name,code,per,pbr,배당수익률):
    self.name = name
    self.code = code
    self.per = per
    self.pbr = pbr
    self.배당수익률 = 배당수익률

  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

위에서 생성한 객체에 set_per 매서드를 호출하여 per 값을 12.75로 수정해보세요.

코드

class Stock:
  def __init__(self,name,code,per,pbr,배당수익률):
    self.name = name
    self.code = code
    self.per = per
    self.pbr = pbr
    self.배당수익률 = 배당수익률

  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

삼성 = Stock("삼성전자", "005930", 15.79, 1.33, 2.83)
삼성.set_per(12.75)
print(삼성.per)

실행 결과
12.75

아래의 표를 참조하여 3종목에 대해 객체를 생성하고 이를 파이썬 리스트에 저장하세요. 파이썬 리스트에 저장된 각 종목에 대해 for 루프를 통해 종목코드와 PER을 출력해보세요.

종목명 / 종목코드 / PER / PBR / 배당수익률
삼성전자 / 005930 / 15.79 / 1.33 / 2.83
현대차 / 005380 / 8.70 / 0.35 / 4.27
LG전자 / 006570 / 317.34 / 0.69 / 1.37

코드

class Stock:
  def __init__(self,name,code,per,pbr,배당수익률):
    self.name = name
    self.code = code
    self.per = per
    self.pbr = pbr
    self.배당수익률 = 배당수익률

  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

종목 = []

삼성 = 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)

종목.append(삼성)
종목.append(현대차)
종목.append(LG전자)

for i in 종목:
  print(i.code, i.per)

실행 결과
005930 15.79
005380 8.7
066570 317.34

은행에 가서 계좌를 개설하면 은행이름, 예금주, 계좌번호, 잔액이 설정됩니다. Account 클래스를 생성한 후 생성자를 구현해보세요. 생성자에는 에금주와 초기 잔액만 입력 받습니다. 은행이름은 SC은행으로 계좌번호는 3자리-2자리-6자리 형태로 랜덤하게 생성됩니다.

코드

import random

class Account:
    def __init__(self, name, balance):
        self.name = name
        self.balance = balance
        self.bank = "SC은행"
        num1 = random.randint(0, 999)
        num2 = random.randint(0, 99)
        num3 = random.randint(0, 999999)

        num1 = str(num1).zfill(3)
        num2 = str(num2).zfill(2)
        num3 = str(num3).zfill(6)
        self.account_number = num1 + '-' + num2 + '-' + num3

kim = Account("김민수", 100)
print(kim.name)
print(kim.balance)
print(kim.bank)
print(kim.account_number)

실행 결과
김민수
100
SC은행
270-76-714596

클래스 변수 / 클래스 변수 출력 / 입금 메서드 / 출금 메서드

클래스 변수를 사용해서 Account 클래스로부터 생성된 계좌 객체의 개수를 저장하세요.

코드

import random

class Account:
    # class variable
    account_count = 0

    def __init__(self, name, balance):
        self.name = name
        self.balance = balance
        self.bank = "SC은행"

        num1 = random.randint(0, 999)
        num2 = random.randint(0, 99)
        num3 = random.randint(0, 999999)

        num1 = str(num1).zfill(3)      # 1 -> '1' -> '001'
        num2 = str(num2).zfill(2)      # 1 -> '1' -> '01'
        num3 = str(num3).zfill(6)      # 1 -> '1' -> '0000001'
        self.account_number = num1 + '-' + num2 + '-' + num3  # 001-01-000001

        Account.account_count += 1


kim = Account("김민수", 100)
print(Account.account_count)
lee = Account("이민수", 100)
print(Account.account_count)

실행 결과
1
2

Account 클래스로부터 생성된 계좌의 개수를 출력하는 get_account_num() 메서드를 추가하세요.

코드

import random

class Account:
    # class variable
    account_count = 0

    def __init__(self, name, balance):
        self.name = name
        self.balance = balance
        self.bank = "SC은행"

        # 3-2-6
        num1 = random.randint(0, 999)
        num2 = random.randint(0, 99)
        num3 = random.randint(0, 999999)

        num1 = str(num1).zfill(3)      # 1 -> '1' -> '001'
        num2 = str(num2).zfill(2)      # 1 -> '1' -> '01'
        num3 = str(num3).zfill(6)      # 1 -> '1' -> '0000001'
        self.account_number = num1 + '-' + num2 + '-' + num3  # 001-01-000001
        Account.account_count +=1

    @classmethod
    def get_account_num(cls):
        print(cls.account_count)     # Account.account_count


kim = Account("김민수", 100)
lee = Account("이민수", 100)
kim.get_account_num()

실행 결과
2

Account 클래스에 입금을 위한 deposit 메서드를 추가하세요. 입금은 최소 1원 이상만 가능합니다.

코드

import random

class Account:
  account_count = 0  
  def __init__(self, name, balance):
        self.name = name
        self.balance = balance
        self.bank = "SC은행"
        num1 = random.randint(0, 999)
        num2 = random.randint(0, 99)
        num3 = random.randint(0, 999999)

        num1 = str(num1).zfill(3)
        num2 = str(num2).zfill(2)
        num3 = str(num3).zfill(6)
        self.account_number = num1 + '-' + num2 + '-' + num3
        Account.account_count += 1

  @classmethod
  def get_account_num(cls):
        print(cls.account_count)
    
  def deposit(self, amount):
        if amount >= 1:
            self.balance += amount

Account 클래스에 출금을 위한 withdraw 메서드를 추가하세요. 출금은 계좌의 잔고 이상으로 출금할 수는 없습니다.

코드

import random

class Account:
  account_count = 0  
  def __init__(self, name, balance):
        self.name = name
        self.balance = balance
        self.bank = "SC은행"
        num1 = random.randint(0, 999)
        num2 = random.randint(0, 99)
        num3 = random.randint(0, 999999)

        num1 = str(num1).zfill(3)
        num2 = str(num2).zfill(2)
        num3 = str(num3).zfill(6)
        self.account_number = num1 + '-' + num2 + '-' + num3
        Account.account_count += 1

  @classmethod
  def get_account_num(cls):
        print(cls.account_count)
    
  def deposit(self, amount):
        if amount >= 1:
            self.balance += amount
            
  def withdraw(self, amount):
        if self.balance > amount:
            self.balance -= amount

k = Account("kim", 100)
k.deposit(100)
k.withdraw(90)
print(k.balance)

실행 결과
110

0개의 댓글