Python Basics - Class

Jayson Hwang·2022년 4월 30일
0

17. Class

  • Class객체 지향 프로그래밍(Object Oriented Programming)을 위한 도구로 사용되며, 객체를 정의하는 설계도

  • 클래스(Class)는 사용자가 새로운 타입(형식)을 정의하는 것이며, 객체(Object)는 클래스의 인스턴스(instance), 즉, 새로운 형을 사용해서 만든 것


17-1. Class 정의

class ClassName:
	...# 내용 코드
  • class이름은 항상 대문자로 시작한다. 이어진 단어들은 space없이 대문자로 받아주면된다.
    ex) SomeReallyLongClassName
class Car:
	pass
  • class가 정의되면, class로 부터 실체화(instantiate)할 수 있고,
    아래와 같이 함수를 호출하듯 클래스도 호출하면 된다.
hyundai = Car()
bmw = Car()

🚀 Car class를 실체(instance)한 것이 hyundai와 bmw라는 객체(object)


17-2. Class Attribute(속성)

  • class에 정의되는 공통 요소를 class의 attribute 라고 함.
    (class안에서 정의해주는 함수(function)은 function이라고 하지않고 method라고 함)
class Car:
    def __init__(self, maker, model, horse_power):
        self.maker       = maker
        self.model       = model
        self.horse_power = horse_power
  • "__init__(생성자)":: class가 실체화 될때 사용되는 함수(Method)
    class가 실체화 될 때 자동으로 __init__ method가 호출

📌 "self"

  • self는 class의 실체(instance)인 객체(object)

  • ex) Car class의 "self"는 Car class의 객체인 "hyundai" 나 "bmw"를 가리킴

  • 그리고, class를 실체화 할때 파이썬이 해당 객체(self)를 자동으로 init함수에 넘겨줌

< Paraphrase >

  1. __init__메소드는 클래스가 실체화 될때 자동으로 호출
  2. __init__메소드의 "self"는 클래스가 실체화된 객체를 넘겨주어야 하며, 파이썬이 자동으로 넘겨줌
  3. __init__메소드의 "self"는 항상 정의되어야 있어야 하며 맨 처음 parameter로 정의 되어야함 (그래야 파이썬이 알아서 넘겨줄 수 있으므로)
ex) class Car:
    def __init__(self, maker, model, horse_power):

17-3. Class Method

  • Methodmove, eat 등 객체(object)가 행할 수 있는 어떠한 action의 느낌
class Car:
    def __init__(self, maker, model, horse_power):
        self.maker       = maker
        self.model       = model
        self.horse_power = horse_power

    def honk(self):
        return "빠라바라빠라밤"
        
        
hyundai = Car("현대", "제네시스", 500)
hyundai.honk()

> "빠라바라빠라밤"

::: if 경적소리에 차의 제조사명이 들어가야 한다면,

class Car:
    def __init__(self, maker, model, horse_power):
        self.maker       = maker
        self.model       = model
        self.horse_power = horse_power

    def honk(self):
        return f"{self.maker} 빠라바라빠라밤"


hyundai = Car("현대", "제네시스", 500)
hyundai.honk()

> "현대 빠라바라빠라밤"        

Reference

https://hleecaster.com/python-class/ :: class 관련 기본지식
https://junstar92.tistory.com/65 :: class 관련 기본지식

profile
"Your goals, Minus your doubts, Equal your reality"

0개의 댓글