AI학습 11

이유진·2024년 6월 27일

-- 16.상속.ipynb --

1. 상속

  • 기존의 정의해둔 클래스의 기능을 그대로 물려 받음
  • 기존 클래스에 기능 일부를 추가하거나, 변경하여 새로운 클래스를 정의함
  • 코드를 재사용 할 수 있게 됨
  • 안정적이고 유지보수에 용이함
  • 상속을 해주는 기존 클래스를 부모, parent, super, base 클래스라고 부름
  • 상속을 받는 새로운 클래스는 자식, child, sub 클래스라고 부름

class Animal:
def init(self, name, age):
self.name = name
self.age = age

def eat(self, food):
print(f'{self.name}은(는) {food}을(를) 먹는다.')

def sleep(self, hour):
print(f'{self.name}은(는) {hour}시간 잡니다.')

animal = Animal('앙마',1)
animal.eat('닭가슴살')

class Dog(Animal):
pass

mydog = Dog('아리',7)
mydog.eat('닭가슴살')
mydog.sleep(10)

class A :
def init(self, data, name) :
self.data = data
self.name = name

def point() :
print('여기서만 출력.')

A.point() # 질문 할 거 staticmethod이랑 지금 적은 코드랑 다른것?x

2. 메소드 오버라이딩

class Animal:
def init(self, name, age):
self.name = name
self.age = age

def eat(self, food):
print(f'{self.name}은(는) {food}을(를) 먹는다.')

def sleep(self, hour):
print(f'{self.name}은(는) {hour}시간 잡니다.')

class Dog(Animal) :

생성자도 오버라이딩 가능!! 중요!!

def init(self, name, age, breed) :
self.name = name
self.age = age
self.breed = breed

def eat(self, food) :
print(f'{self.name}은(는) {food}을(를) 아주 맛있게 먹는다.')

tomy = Dog('토미', 2, '말라뮤트')
tomy.eat('개껌')
print(tomy.breed)

3. 다중상속

class Animal:
def init(self, name, age):
self.name = name
self.age = age

def eat(self, food):
print(f'{self.name}은(는) {food}을(를) 먹는다.')

def sleep(self, hour):
print(f'{self.name}은(는) {hour}시간 잡니다.')

class Human :
def init(self, name, age, IQ) :
self.name = name
self.age = age
self.IQ = IQ

def study(self, hour) :
print(f'{self.name}은(는) {hour}시간 동안 공부합니다.')

def eat(self, food):
print(f'{self.name}은(는) {food}을(를) 야무지게 먹는다.')

각 부모클래스에 같은 이름의 메소드(생성자)가 존재한다면

앞에 적어준 부모 클래스의 메소드가 실행된다.

class Student(Human,Animal) :

자식 클래스에서 재정의를 한다면

자식 클래스로 객체를 만들어 메소드를 실행 할 때

무조건 재정의된 메소드(생성자)가 우선이다.

def init(self, name, age, IQ, grade) :
self.name = name
self.age = age
self.IQ = IQ
self.grade = grade

def printIQ(self) :
print('내 IQ 는',self.IQ)

Eugene = Student('이유진', 25, 133, 'A')
Eugene.eat('밥')
Eugene.IQ
Eugene.printIQ()

-- 17.스페셜_메소드.ipynb --

1. 스페셜 메소드(Spectial Method)

  • 로 시작해서 로 끝나는 특수함수
  • 해당 메소드들을 재구현하면 객체에 여러가지 파이썬 내장 함수나 연산자에 원하는 기능을 부여할 수 있음.

class Point :
def init(self, x, y) :
self.x = x
self.y = y

def str(self) :
return (f'({self.x},{self.y})')

def print_obj(self) :
print(f'({self.x},{self.y})')

def add(self, pt) :
isInt = isinstance(pt, int)
if isInt :
new_x = self.x + pt
new_y = self.y + pt
else :
new_x = self.x + pt.x
new_y = self.y + pt.y
return Point(new_x,new_y)

p1 = Point(49,51)
p1.print_obj()

모든 객체를 출력할 때는 str() 이 생략되어있음.

print(p1) # str을 재구현 하기 전에 확인해보니 위치정보 값이 문자형으로 들어가있다.

print(str(p1))

print(p1)

p1 = Point(49,51)
p2 = Point(100,111)
p3 = p1 + p2 # return Point(new_x,new_y)

print(p1+p2)
print(p3)

p1 = Point(49,51)

print(p1+5)

profile
독해지자

0개의 댓글