라일락 꽃이 피는 날

[Python] Class (클래스) 본문

프로그래밍/Python

[Python] Class (클래스)

eunki 2021. 8. 16. 22:31
728x90

Class (클래스)

- 실세계의 것을 모델링하여 속성(attribute)과 동작(method)을 갖는 데이터 타입이다.

- 다루고자 하는 데이터(변수)와 데이터를 다루는 연산(함수)을 하나로 캡슐화하여 클래스로 표현한다.

 

Object (객체)

- 클래스로 생성되어 구체화된 객체(인스턴스)다.

- 실제로 class가 인스턴스화되어 메모리에 상주하는 상태를 의미한다.

- 객체를 생성하기 위해서는 객체의 모체가 되는 클래스를 미리 선언해야 한다.

 

 

 


Class 선언

class Person:
    pass

bob = Person()
cathy = Person()

print(type(bob))  # <class '__main__.Person'>
print(type(cathy))  # <class '__main__.Person'>
a = list()
b = list()

print(type(a))  # <class 'list'>
print(type(b))  # <class 'list'>

 

 

 

init (self)

- 생성자, 클래스 인스턴스가 생성될 때 호출된다.

- self 인자는 항상 첫 번째에 오며, 자기 자신을 가리킨다.

- 생성자에서는 해당 클래스가 다루는 데이터를 정의한다.

class Person:
    def __init__(self):
        self.name = 'Kate'
        self.age = 10
        
p1 = Person()
p2 = Person()

p1.name = 'aaron'
p1.age = 20

print(p1.name, p1.age)  # aaron 20
print(p2.name, p2.age  # Kate 10
class Person:
    def __init__(self, name, age=10):
        self.name = name
        self.age = age
        
p1 = Person('Bob', 30)
p2 = Person('Kate', 20)
p3 = Person('Aaron')

print(p1.name, p1.age)  # Bob 30
print(p2.name, p2.age)  # Kate 20
print(p3.name, p3.age)  # Aaron 10

 

 

 

method (멤버 함수)

- 해당 클래스의 object에서만 호출이 가능하다.

- 메쏘드는 객체 레벨에서 호출되며, 해당 객체의 속성에 대한 연산을 수행한다.

class Counter:
    def __init__(self):
        self.num = 0
        
    def increment(self):
        self.num += 1
    
    def reset(self):
        self.num = 0
    
    def print_current_value(self):
        print('현재값은:', self.num)
        
        
c1 = Counter()
c1.print_current_value()  # 현재값은: 0

c1.increment()
c1.increment()
c1.increment()
c1.print_current_value()  # 현재값은: 3

c1.reset()
c1.print_current_value()  # 현재값은: 0

c2 = Counter()
c2.increment()
c2.print_current_value()  # 현재값은: 1

 

 

 

method type

1. instance method - 객체로 호출

  메쏘드는 객체 레벨로 호출 되기 때문에, 해당 메쏘드를 호출한 객체에만 영향을 미친다.

 

2. class method - 클래스로 호출

  클래스 메쏘드의 경우 클래스 레벨로 호출되기 때문에, 클래스 멤버 변수만 변경 가능하다.

class Math:
    @staticmethod
    def add(a, b):
        return a + b
    
    @staticmethod
    def multiply(a, b):
        return a * b
    
Math.add(10, 20)  # 30
Math.multiply(10, 20)  # 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 __len__(self):
        return self.x ** 2 + self.y ** 2
        
    def __str__(self):
        return '({}, {})'.format(self.x, self.y)
      
      
p1 = Point(3, 4)
p2 = Point(2, 7)

p3 = p1 + p2
p4 = p1 - p2

p5 = p1 * 3

print(p1[0])  # 3
print(p1[1])  # 4

print(len(p1))  # 25

print(p1)  # (3, 4)
print(p2)  # (2, 7)
print(p3)  # (5, 11)
print(p4)  # (1, -3)
print(p5)  # (9, 12)
728x90

'프로그래밍 > Python' 카테고리의 다른 글

[Python] 정규 표현식 (regular expression) 1  (0) 2021.08.16
[Python] Class Inheritance (상속)  (0) 2021.08.16
[Python] Package, Module  (0) 2021.06.15
[Python] fileopen  (0) 2021.06.15
[Python] strftime, strptime  (0) 2021.06.14