클래스를 사용하면 같은 코드를 활용하여 독립적인 객체를 생성할 수 있다.
<aside> 💡 객체(Object)와 인스턴스(Instance)
인스턴스는 특정 객체가 어떤 클래스의 객체인지의 관계 위주 설명에 사용된다.
a = Object()
에서
a
는 객체
a
는 Object
클래스의 인스턴스
</aside>
class 클래스명:
[클래스 변수]
def __init__(self): #생성자
[객체 변수]
[메서드]
# 객체 생성
객체이름 = 클래스명(초기인자1, 초기인자2)
클래스 변수와 객체 변수
class Car:
color = "red"
a = Car()
# 클래스 변수값을 바꿀 때에는 클래스 이름으로 접근해야 모든 클래스에서 바뀐다.
Car.color = "blue"
print(a.color)
'''
<결과>
blue
'''
class Car:
color = "red"
a = Car()
# 객체 이름으로 접근하면 a객체에 color라는 동일한 이름의 객체 변수가 생성되는 것이다.
a.color = "blue"
print(a.color)
print(Car.color)
'''
<결과>
blue
red
'''
# 새로 생성된 동일한 객체이름을 우선 가리켜 값은 블루가 나오지만 클래스 변수 값은 동일하다.
생성자 (Constructor)
객체에 초깃값을 전달하기 위해 자동으로 호출되는 이름이 __init__
인 메소드이다.
class Car:
# self는 객체 자신
def __init__(self, color, ctype): #생성자
self.color = color
self.ctype = ctype
a = Car("red", "suv") # 객체 생성시 초깃값을 전달
print("%s %s" % (a.color, a.ctype))
'''
<결과>
red suv
'''
상속 (Inheritance)
아들 클래스를 만들 때 부모 클래스의 기능을 물려받을 수 있으며 새로 추가하거나 변경할 수 있는 기능이다.
class Car:
def __init__(self, color):
self.color = color
class Sonata(Car):
pass # 기능 추가는 없다
a = Sonata("red") # 부모 클래스의 생성자를 그대로 사용
print(a.color)
'''
<결과>
red
'''
메서드 오버라이딩
부모 클래스에 있는 메서드를 동일한 이름으로 다시 만드는 것을 말한다. 이렇게 메서드를 오버라이딩하면 새로 만든 메서드가 호출된다.
class Car:
def __init__(self, color):
self.color = color
def paint(self):
self.color = "black"
class Sonata(Car):
def paint(self, new_color): # 메서드 오버라이딩
self.color = new_color
a = Sonata("red")
a.paint("blue") # 해당 메서드 호출
print(a.color)
'''
<결과>
blue
'''