#class inheritance
class Animal():
def __init__(self):
print("ANIMAL CREATED")
def who_am_i(self):
print("I am an animal")
def eat(self):
print("I am eating")
<init> method: initialize method(초기화 메서드)를 말한다. class를 생성했을때 초기화를 시켜주는 특수한 메서드이다. 메서드는 일반함수와의 구분을 위한것으로 클래스의 함수를 메소드라고 부름. 파이썬에는 여러 형태의 메소드가 있는데 여기서 칭하는 특정 함수 내 메소드와 여타 메소드를 구분해야함.
<init> method의 가장 처음으로 호출되어야 되는 첫번째 인자는 self이다. 다른 인자명을 적어도 작동은 하나 파이썬에서는 Self로 통일하는 것이 오랜 관습임.
class Dog(Animal):
def __init__(self):
Animal.__init__(self)
print("Dog Created")
def who_am_i(self):
print("I am a dog!")
def mydog_bark(self):
print("Whoof!")
mydog = Dog()
mydog.eat()
mydog.who_am_i()
mydog.mydog_bark()
#polymorphism
class Wolf():
def __init__(self, name):
self.name = name
def speak(self):
return self.name + " says Ahoo!~"
class Cat():
def __init__(self, name):
self.name = name
def speak(self):
return self.name + " says Meow!~"
lulu = Wolf("lulu")
nabi = Cat("nabi")
print(lulu.speak())
print(nabi.speak())
for pet in [lulu, nabi]:
print(type(pet))
print(type(pet.speak))
def pet_speak(pet):
print(pet.speak())
pet_speak(nabi)
#abstract class
class Animal2():
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError("Subclass must implement this abstract method")
class Wolf2(Animal2):
def speak(self):
return self.name + " says Ahoo!~"
class Cat2(Animal2):
def speak(self):
return self.name + " says Meow!~"
jack = Wolf2("Jack")
isis = Cat2("Isis")
print(jack.speak())
print(isis.speak())
class Account():
def __init__(self, owner, balance):
self.owner = owner
self.balance = balance
def deposit(self, damount):
self.balance = self.balance + damount
print("Hello, {}. We added '{}' to the balance, and the current balance is '{}'".format(self.owner, damount, self.balance))
#여기서 print 대신 return은 못 쓰는 걸까?
def withdraw(self, wamount):
if self.balance >= wamount:
self.balance = self.balance - wamount #여기서 시작을 self-balance로 안해주면 추후 남은 잔고가 반영이 안됨.
print("Hello, {}. We subtracted '{}' to the balance, and the current balance is '{}'".format(self.owner, wamount, self.balance))
elif self.balance < wamount:
self.balance = -(self.balance - wamount)
print(f"Sorry, that exceeds your withdrawl limit for '{self.balance}'")
acct1 = Account(owner = 'Jose', balance = 100)
acct1.deposit(50)
acct1.withdraw(100)
acct1.withdraw(30)
acct1.withdraw(2000)