Programing/Python
#클래스와 인스턴스
CouqueD'asse
2022. 7. 1. 15:05
class란?
- 실세계의 것을 모델링하여 속성(attribute)와 동작(method)를 갖는 데이터 타입
- python에서의 string, int, list, dict.. 모두가 다 클래스로 존재
- 예를들어 학생이라는 클래스를 만든다면, 학생을 나타내는 속성과 학생이 행하는 행동을 함께 정의 할 수 있음
- 따라서, 다루고자 하는 데이터(변수) 와 데이터를 다루는 연산(함수)를 하나로 캡슐화(encapsulation)하여 클래스로 표현
- 모델링에서 중요시 하는 속성에 따라 클래스의 속성과 행동이 각각 달라짐
object 란?
- 클래스로 생성되어 구체화된 객체(인스턴스)
- 파이썬의 모든 것(int, str, list..etc)은 객체(인스턴스)
- 실제로 class가 인스턴스화 되어 메모리에 상주하는 상태를 의미
- class가 빵틀이라면, object는 실제로 빵틀로 찍어낸 빵이라고 비유 가능
class 선언하기
- 객체를 생성하기 위해선 객체의 모체가 되는 class를 미리 선언해야 함
class Person :
pass
bob = Person()
cathy = Person()
a = list()
b = list()
print(type(bob), type(cathy))
print(type(a), type(b))
<class '__main__.Person'> <class '__main__.Person'>
<class 'list'> <class 'list'>
init (self)
- 생성자, 클래스 인스턴스가 생성될 때 호출됨
- self인자는 항상 첫번째에 오며 자기 자신을 가리킴
- 이름이 꼭 self일 필요는 없지만, 관례적으로 self로 사용
- 생성자에서는 해당 클래스가 다루는 데이터를 정의
- 이 데이터를 멤버 변수(member variable) 또는 속성(attribute)라고 함
class Person:
def __init__(self):
self.name = 'Bob'
self.age = 10
p1 = Person()
print(p1.name, p1.age)
p1.name = 'Kate'
p1.age = 20
print(p1.name, p1.age)
Bob 10
Kate 20
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person('Lady', 24)
print(p1.name, p1.age)
Lady 24
class Person:
def __init__(self, name, age = 30):
self.name = name
self.age = age
p1 = Person('Lady')
print(p1.name, p1.age)
Lady 30
mehtod 정의
- 멤버함수라고도 하며, 해당 클래스의 object에서만 호출가능
- 메쏘드는 객체 레벨에서 호출되며, 해당 객체의 속성에 대한 연산을 행함
- {obj}.{method}() 형태로 호출됨
class Counter:
def __init__(self):
self.num = 0
def increment(self):
self.num += 1
def reset(self):
self.num = 0
def current_vlaue_print(self):
print('current valuie : ', self.num)
c1 = Counter()
c1.current_vlaue_print()
c1.increment()
c1.increment()
c1.current_vlaue_print()
c1.reset()
c1.current_vlaue_print()
current valuie : 0
current valuie : 2
current valuie : 0
Class Inheritance (상속)
- 기존에 정의해둔 클래스의 기능을 그대로 물려받을 수 있다.
- 기존 클래스에 기능 일부를 추가하거나, 변경하여 새로운 클래스를 정의한다.
- 코드를 재사용할 수 있게된다.
- 상속 받고자 하는 대상인 기존 클래스는 (Parent, Super, Base class 라고 부른다.)
- 상속 받는 새로운 클래스는(Child, Sub, Derived class 라고 부른다.)
- 의미적으로 is-a관계를 갖는다
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def eat(self, food):
print('{}은 {}를 먹습니다.'.format(self.name, food))
def sleep(self, minute):
print('{}은 {}시간 잡니다.'.format(self.name, minute))
def work(self, minute):
print('{}은 {}시간 일합니다.'.format(self.name, minute))
class Student(Person):
def __init__(self, name, age):
self.name = name
self.age = age
class Employee(Person):
def __init__(self, name, age):
self.name = name
self.age = age
bob = Student('Bob', 20)
bob.eat('BBQ')
bob.sleep(6)
bob.work(5)
cathy = Employee('Cathy', 30)
cathy.eat('BBQ')
cathy.sleep(6)
cathy.work(5)
Bob은 BBQ를 먹습니다.
Bob은 6시간 잡니다.
Bob은 5시간 일합니다.
Cathy은 BBQ를 먹습니다.
Cathy은 6시간 잡니다.
Cathy은 5시간 일합니다.
method override
- 부모 클래스의 method를 재정의(override)
- 하위 클래스(자식 클래스) 의 인스턴스로 호출시, 재정의된 메소드가 호출됨
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def eat(self, food):
print('{}은 {}를 먹습니다.'.format(self.name, food))
def sleep(self, minute):
print('{}은 {}시간 잡니다.'.format(self.name, minute))
def work(self, minute):
print('{}은 {}시간 일합니다.'.format(self.name, minute))
class Student(Person):
def __init__(self, name, age):
self.name = name
self.age = age
def work(self, minute):
print('{}은 {}시간 공부합니다.'.format(self.name, minute))
class Employee(Person):
def __init__(self, name, age):
self.name = name
self.age = age
bob = Student('Bob', 20)
bob.eat('BBQ')
bob.sleep(6)
bob.work(5)
cathy = Employee('Cathy', 30)
cathy.eat('BBQ')
cathy.sleep(6)
cathy.work(5)
Bob은 BBQ를 먹습니다.
Bob은 6시간 잡니다.
Bob은 5시간 공부합니다.
Cathy은 BBQ를 먹습니다.
Cathy은 6시간 잡니다.
Cathy은 5시간 일합니다.
super
- 하위클래스(자식 클래스)에서 부모클래스의 method를 호출할 때 사용
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def eat(self, food):
print('{}은 {}를 먹습니다.'.format(self.name, food))
def sleep(self, minute):
print('{}은 {}시간 잡니다.'.format(self.name, minute))
def work(self, minute):
print('{}은 {}시간 일합니다.'.format(self.name, minute))
class Employee(Person):
def __init__(self, name, age):
self.name = name
self.age = age
def work(self, minute):
super().work(minute)
print('{}은 {}시간 업무를 합니다.'.format(self.name, minute))
cathy = Employee('Cathy', 30)
cathy.eat('BBQ')
cathy.sleep(6)
cathy.work(5)
Cathy은 BBQ를 먹습니다.
Cathy은 6시간 잡니다.
Cathy은 5시간 일합니다.
Cathy은 5시간 업무를 합니다.
self
- 파이썬의 method는 항상 첫번째 인자로 self를 전달
- self는 현재 해당 메쏘드가 호출되는 객체 자신을 가리킴
- C++/C#, Java의 this에 해당
- 역시, 이름이 self일 필요는 없으나, 위치는 항상 맨 처음의 parameter이며 관례적으로 self로 사용
method type
- instance method - 객체로 호출
- 메쏘드는 객체 레벨로 호출 되기 때문에, 해당 메쏘드를 호출한 객체에만 영향을 미침
- class method - class로 호출
- 클래스 메쏘드의 경우, 클래스 레벨로 호출되기 때문에, 클래스 멤버 변수만 변경 가능
# class method
class Math:
@staticmethod
def add(a, b):
return a + b
@staticmethod
def multiply(a, b):
return a * b
Math.add(10, 20)
Math.multiply(10, 20)
30
200
special method
- __로 시작 __로 끝나는 특수 함수
- 해당 메쏘드들을 구현하면, 커스텀 객체에 여러가지 파이썬 내장 함수나 연산자를 적용 가능
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, pt):
new_x = self.x + pt.x
new_y = self.y + pt.y
return Point(new_x, new_y)
def __sub__(self, pt):
new_x = self.x - pt.x
new_y = self.y - pt.y
return Point(new_x, new_y)
def __mul__(self, factor):
return Point(self.x * factor, self.y * factor)
def __getitem__(self, index):
if index == 0:
return self.x
elif index == 1:
return self.y
else:
return -1
def get_y(self):
return self.y
def __len__(self):
return self.x ** 2 + self.y ** 2
def __str__(self):
return '({}, {})'.format(self.x, self.y)
p1 = Point(1, 3)
p2 = Point(3, 5)
p3 = p1 + p2
p4 = p1 - p2
p5 = p1 * 3
print(p1[0])
print(len(p1))
print(p1)
print(p2)
print(p3)
print(p4)
print(p5)
1
10
(1, 3)
(3, 5)
(4, 8)
(-2, -2)
(3, 9)