# 클래스 생성자 / 소멸자
class Person(object):
def __init__(self, name):
self.name = name
def __del__(self):
print('good bye')
def say(self):
print('hello')
self.run(2)
def run(self, num):
print('run' * num)
person = Person('Mike')
person.say()
# del 을 사용하면 강제로 소멸자가 호출되게 할 수 있다.
del person
####################################################################
# 클래스 상속
class Car(object):
def __init__(self, model=None):
self.model = model
def run(self):
print('run')
class Toyota(Car):
def run(self):
print('fast')
class Tesla(Car):
def __init__(self, model='Model S', enable_auto_run=False):
super().__init__(model)
self._enable_auto_run = enable_auto_run
# enable_auto_run 을 readonly 로 만들기
@property
def enable_auto_run(self):
return self._enable_auto_run
def run(self):
print('super fast')
def auto_run(self):
print('auto run')
car = Car()
car.run()
toyota = Toyota('Lexus')
toyota.run()
tesla = Tesla('Model S')
tesla.run()
tesla.auto_run()
# enable_auto_run 은 readonly
tesla.enable_auto_run = True # AttributeError: can't set attribute 'enable_auto_run'
####################################################################
# abstract class
import abc
# abc.ABC 를 상속받아 생성: Person 객체를 직접 생성 불가능하게 함
class Person(abc.ABC):
def __init__(self, age=1):
self.age = age
@abc.abstractmethod
def drive(self):
pass
class Adult(Person):
def drive(self):
print("ok")
person = Adult()
person.drive()
####################################################################
# 다중 상속
class A(object):
def talk(self):
print('talk')
def run(self):
print('A run')
class B(object):
def run(self):
print('B run')
class AB(A, B):
def fly(self):
print('fly')
ab = AB()
# AB(A, B) 로 정의되어 있을 경우 A 에 있는 method 를 사용한다.
ab.run() # A run
ab.fly() # fly
####################################################################
# 클래스 변수
class Book(object):
# 모든 클래스 오브젝트들이 공유
kind = 'comic'
def __init__(self, name) -> None:
self.name = name
def info(self):
print(self.kind, self.name)
book = Book('Dragon Ball')
book.info() # comic Dragon Ball
####################################################################
# class method / static method
class Circle(object):
kind = 'plane'
def __init__(self, r):
self.x = r
# 주로 factory method 로 활용
@classmethod
def default_circle(cls):
return cls(100)
@staticmethod
def about(radius):
print(f'about circle: {radius}')
a = Circle(9)
print(a.kind) # plane
print(a.x) # 9
b = Circle.default_circle()
print(b.x) # 100
print(Circle.kind) # plane
print(Circle.x) # AttributeError: type object 'Circle' has no attribute 'x'
print(Circle.about(3)) # about circle: 3
####################################################################
# 특수 메소드
class Word(object):
def __init__(self, text):
self.text = text
# str()
def __str__(self):
return 'Word!!!!'
# len()
def __len__(self):
return len(self.text)
# +
def __add__(self, word):
return self.text.lower() + word.text.lower()
# ==
def __eq__(self, word):
return self.text.lower() == word.text.lower()