클래스 정의 외부에서 볼 수 없도록 하는 속성에 대한 네이밍 컨벤션(naming convention)이 있다. 속성 이름 앞에 두 언더스코어(__)를 붙이면 된다.
'
class Duck():
def __init__(self, input_name):
self.__name = input_name
@property
def name(self):
return self.__name
@name.setter
def name(self, input_name):
self.__name = input_name
> fowl = Duck('Howard')
> fowl.name
'Howard'
> fowl.name = 'aaa'
> fowl.name
'aaa'
class A():
count = 0
def __init__(self):
A.count += 1
def exclaim(self):
print("IAM")
@classmethod
def kids(cls):
print("A has ", cls.count)
@staticmethod
def hello():
print("Hello")
> easy_a = A()
> easy_aa = A()
> easy_aaa = A()
> A.kids()
A has 3
상속 - 자식 is-a 부모
컴포지션(어그리게이션) - X has -a Y
class Bill():
def __init__(self, description):
self.description = description
class Tail():
def __init__(self, length):
self.length = length
class Duck():
def __init__(self, bill, tail):
self.bill = bill
self.tail = tail
def about(self):
print(self.bill.description, self.tail.length)
> tail = Tail('tail')
> bill = Bill('wide orange')
> duck = Duck(bill, tail)
> duck.about()
wide orange tail
튜플의 서브 클래스. 이름과 위치로 값에 접근 할 수 있다.
두 인자를 취하는 namedtuple 함수
class Bill():
def __init__(self, description):
self.description = description
class Tail():
def init(self, length):
self.length = length
class Duck():
def init(self, bill, tail):
self.bill = bill
self.tail = tail
def about(self):
print(self.bill.description, self.tail.length)
from collections import namedtuple
Duck = namedtuple('Duck', 'bill tail')
Duck
<class 'main.Duck'>
Duck('widd', 'long')
Duck(bill='widd', tail='long')
duck = Duck('widd', 'long')
duck
Duck(bill='widd', tail='long')
parts = {'bill': 'orage', 'tail': 'long'}
duck2 = Duck(**parts)
duck2
Duck(bill='orage', tail='long')```