파이썬 객체

파이썬에서 지원하는 클래스와 이를 활용한 객체 지향 프로그래밍을 소개한다.

객체 지향에서 나오는 개념들을 파이썬에서는 어떻게 코드로 표현하는지 살펴본다.

  • an identity(id)
  • a value (mutable or immutable)
    • Mutable : Dictionary, List
    • Immutable : String, Integer, Tuple

파이썬 클래스 작명법(네이밍)

  • CamelCase
  • 숫자로 시작하면 안된다.
  • 명사

Identity (ID)

>>> sonic = 4

>>> id(sonic)

140417022626656

>>>

A Value (Mutable or Immutable)

Mutable

>>> a = []

>>> id(a)
4381159296

>>> a.append(1)

>>> a
[1]

>>> id(a)
4381159296

>>>

Immutable

>>> a = 10

>>> id(a)
140417022626512

>>> a = a + 1

>>> id(a)
140417022626488

자동차 기본 클래스

 class Car(object):

    NORTH = 0
    EAST = 1
    SOUTH = 2
    WEST = 3

    # 생성자
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y
        self.direction = self.NORTH

    def turn_right(self):
        self.direction += 1
        self.direction = self.direction % 4

    def turn_left(self):
        self.direction -= 1
        self.direction = self.direction % 4

    def move(self, distance):
        if self.direction == self.NORTH:
            self.y += distance
        elif self.direction == self.SOUTH:
            self.y -= distance
        elif self.direction == self.EAST:
            self.x += distance
        else:
            self.x -= distance

    def position(self):
        return (self.x, self.y)

정적메소드

class Car(object):
    @staticmethod
    def drive():
        # 운전한다.

Car.drive() # 메서드를 함수처럼 호출

Subclassing

results matching ""

    No results matching ""