λ€νμ±
- κ°μ λͺ¨μμ μ½λκ° λ€λ₯Έ λμμ νλ κ²
- μ½λμ μμ μ€μ΄κ³ , μ¬λ¬ κ°μ²΄ νμ
μ νλμ νμ
μΌλ‘ κ΄λ¦¬κ° κ°λ₯νμ¬ μ μ§ λ³΄μμ μ’λ€.
- λ©μλ μ€λ²λΌμ΄λ©λ λ€νμ±μ ν μ
μμ 1)
#λ€νμ± μμ 1
class Person:
def __init__(self, name):
self.name = name
def work(self):
print(self.name + " works hard")
clas
s Student(Person):
def work(self):
print(self.name + ' studies hard')
class Engineer(Person):
def work(self):
print(self.name + "develope someting")
student = Student("Dave")
deceloper = Engineer("David")
student.work()
deceloper.work()
μμ 2)
# λ€νμ± μμ 2
#ν΄λμ€ λͺ
λ§λ€λ₯΄κ³ μμ μλλ΄μ©(λ©μλ) κ° κ°μ. κ΄λ¦¬κ° λ§€μ° μ©μ΄ν¨.
class Elf:
def __init__(self, name):
self.name = name
def attack(self):
print("λ§λ² 곡격.")
class Fighter:
def __init__(self,name):
self.name = name
def attack(self):
print("주먹 곡격.")
elf = Elf("Dave")
fighter = Fighter('Anthony')
ourteam = [elf, fighter]
for attacker in ourteam:
attacker.attack()
Porperty
μμ 1)
# property μμ 1
class Person():
def __init__(self):
self.__age = 0
@property
def age(self):
return self.__age
@age.setter
def age(self, value):
self.__age = value
james = Person()
james.age = 20 #μΈμ€ν΄μ€.μμ± νμμΌλ‘ μ κ·Όνμ¬ κ° μ μ₯
print(james.age)# μΈμ€ν΄μ€.μμ± νμμΌλ‘ κ°μ κ°μ Έμ΄
μμ 2)
# property μμ 2
class Person():
def __init__(self):
self.__name = 'hong'
@property
def name(self):
return self.__name
@name.setter
def name(self, name):
self.__name = name
person = Person()
print(person.name)
person.name = 'park'
print(person.name)