Python | class 클래스 이해하기

지현·2021년 1월 9일
0

Python

목록 보기
5/9

목표: class 클래스 마스터하기

  • *args에 대해서
# 클래스의 위치 인수, 키워드 인수

# *args

class Person:
    def __init__(self, *args):
        self.name = args[0]
        self.age = args[1]
        self.address = args[2]
 

maria = Person(*['마리아', 20, '서울시 서초구 반포동'])
maria.name       # '마리아'
maria.age	 # 20
  • **kwargs에 대해서
    - kwargs는 (key = value) 형태로 함수를 호출
    - 딕셔너리 형태: {'key' : 'value'}
class Person:
    def __init__(self, **kwargs):    # 키워드 인수
        self.name = kwargs['name']
        self.age = kwargs['age']
        self.address = kwargs['address']
        

        
# maria1 & maria2의 차이점은? 
maria1 = Person(name='마리아', age=20, address='서울시 서초구 반포동')
maria2 = Person(**{'name': '마리아', 'age': 20, 'address': '서울시 서초구 반포동'})

maria2.name		#'마리아'
maria2.age		# 20
  • 연습문제
class Knight:
    def __init__(self, health, mana, armor):
        self.health = health
        self.mana = mana
        self.armor = armor
    
    def slash(self):
        print('베기')

x = Knight(health=542.4, mana=210.3, armor=38)
print(x.health, x.mana, x.armor)
x.slash()

# 출력 값
# 542.4 210.3 38
# 베기
  • 연습문제
class Annie:
    def __init__(self, health, mana, ability_power):
        self.health = health
        self.mana = mana
        self.ability_power = ability_power
    
    def tibbers(self):
        self.ability_power = self.ability_power * 0.65 + 400     
        print(f'티버: 피해량 {self.ability_power}')
    
health, mana, ability_power = map(float, input().split())
x = Annie(health=health, mana=mana, ability_power=ability_power)
x.tibbers()

# 출력
# input -> 511.68 334.0 298
# 티버: 피해량 593.7
  • @classmethod 코드 이해하기
# 인스턴스가 생성될 때마다 숫자를 세야 하므로, __init__메서드에서 클래스 속성 count +1

class Person:
    count = 0    # 클래스 속성
 
    def __init__(self):
        Person.count += 1    # 인스턴스가 만들어질 때
                             # 클래스 속성 count에 1을 더함
 
    @classmethod
    def print_count(cls):
        print('{0}명 생성되었습니다.'.format(cls.count))    # cls로 클래스 속성에 접근
 

james = Person()
maria = Person()
 
Person.print_count()    # 2명 생성되었습니다.
  • 연습문제 _ 주관식(?)

표준 입력으로 시:분:초 형식의 시간이 입력됩니다. 다음 소스 코드에서 Time 클래스를 완성하여 시, 분, 초가 출력되게 만드세요.
from_string은 문자열로 인스턴스를 만드는 메서드이며 is_time_valid는 문자열이 올바른 시간인지 검사하는 메서드입니다.
시간은 24시까지, 분은 59분까지, 초는 60초까지 있어야 합니다. 정답에 코드를 작성할 때는 class Time:에 맞춰서 들여쓰기를 해주세요.

class Time:
    def __init__(self, hour, minute, second):
        self.hour = hour
        self.minute = minute
        self.second = second
    
    @classmethod
    def from_string(cls,time_string):
        hour,minute,second=map(int,time_string.split(':'))
        time=cls(hour,minute,second)
        return time
 
    @staticmethod
    def is_time_valid(time_string):
        hour,minute,second=map(int,time_string.split(':'))
        return hour<=24 and minute<=59 and second<=60

    
time_string = input()
if Time.is_time_valid(time_string):
    t = Time.from_string(time_string)
    print(t.hour, t.minute, t.second)
else:
    print('잘못된 시간 형식입니다.')
   
    
 # input:  12:62:43
 # print: 잘못된 시간 형식입니다.
  • 연습문제: super()로 기반 클래스 초기화하기
class Person:
    def __init__(self):
        print('Person __init__')
        self.hello = '안녕하세요.'
 
class Student(Person):
    def __init__(self):
        print('Student __init__')
        super().__init__()                # super()로 기반 클래스의 __init__ 메서드 호출
        self.school = '파이썬 코딩 도장'
 
james = Student()
print(james.school)
print(james.hello)


# 출력
# Student __init__
# Person __init__
# 파이썬 코딩 도장
# 안녕하세요.
  • 연습문제 __ Error
#에러: 기반 클래스 Person의 __init__ 메서드가 호출되지 않았기 때문

class Person:
    def __init__(self):
        print('Person __init__')
        self.hello = '안녕하세요.'
 
class Student(Person):
    def __init__(self):
        print('Student __init__')
        self.school = '파이썬 코딩 도장'
 
james = Student()
print(james.school)
print(james.hello)    # 기반 클래스의 속성을 출력하려고 하면 에러가 발생함

# 출력:
# Student __init__
# 파이썬 코딩 도장
# AttributeError         : 기반 클래스 Person의 __init__ 메서드가 호출되지 않았기 때문

0개의 댓글