[udemy] python 부트캠프_section 21_ 클래스 상속

Dreamer ·2022년 9월 11일
0
post-thumbnail

01. 클래스 상속

  • 클래스를 상속 받으면, 속성 및 행동을 물려받을 수 있다.(attribute, methods)
  • 클래스를 상속 받으려면, 아래와 같은 형식으로 코드를 사용해야 한다.
# before class inheritance
class Animal:
    def __init__(self):
        self.num_eyes = 2

    def breathe(self):
        print("Inhale,exhale.")


class Fish:

    def swim(self):
        print("moving in water.")


nemo = Fish()
nemo.swim()
# after class inheritance 
class Animal:
    def __init__(self):
        self.num_eyes = 2

    def breathe(self):
        print("Inhale,exhale.")


class Fish(Animal):
    def __init__(self):
        super().__init__()

    def swim(self):
        print("moving in water.")


nemo = Fish()
nemo.swim()
nemo.breathe()
  • 상속 받고자 하는 클래스를 () 안에 적어주고, 아래에 def init():, super().init()를 적어줘야 함.
  • 상속받은 methods를 변경하고자 할 때는 다음과 같이 수정한다.

class Fish(Animal):
    def __init__(self):
        super().__init__()

    def breathe(self):
        super().breathe()
        print("doing this underwater.")
  • class 상속 받을 때, super() 부분 생략 가능하다.
class Dog:
    def __init__(self):
        self.temperament = "loyal"

    def bark(self):
        print("Woof,Woof!")


class Labrador(Dog):
    def __init__(self):
        #super().__init__()
        self.temperament = "friendly"

puppy = Labrador()
puppy.bark()
print(puppy.temperament)

02. 리스트와 튜플 슬라이싱

piano_keys = ["a","b","c","d","e","f","g"]
piano_tuple = ("do","re","mi","fa","sol","la","ti")

# list slicing
# c,d,e만 slicing
print(piano_keys[2:5]) # c,d,e

# 2부터 리스트 끝까지 slicing
print(piano_keys[2:]) #c,d,e,f,g

# 처음부터 5까지 slicing
print(piano_keys[:5]) #a,b,c,d,e

# 세번째 인자는 증가값, 리스트 처음부터 끝까지 값 중 하나씩 건너뛰면서 가져오기
print(piano_keys[::2]) #a,c,e,g

# 전체 리스트를 끝에서부터 역순으로 가는 리스트
print(piano_keys[::-1]) #g,f,e,d,c,b,a

# tuple slicing
print(piano_tuple[2:5]) #mi, fa, sol
print(piano_tuple[::-1]) #('ti', 'la', 'sol', 'fa', 'mi', 're', 'do')
profile
To be a changer who can overturn world

0개의 댓글