Python 기초 - 클래스

런던행·2020년 6월 8일
0

Python 기초

목록 보기
8/11

private 네임 맹글링

클래스 정의 외부에서 볼 수 없도록 하는 속성에 대한 네이밍 컨벤션(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'
 

메서드 타입

  • 인스턴스 메서드 : 첫번째 인자 값이 self
  • 클래스 메서드 : 첫번째 인자 값이 cls. 클래스 전체에 영향을 미친다. @classmethod
  • 정적 메서드 : @staticmethod 데커레이터가 붙어 있고, 첫 번째 인자 값이 sef, cls아 아니고 클래스나 객체에 영향을 미치지 못한다.
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')```

profile
unit test, tdd, bdd, laravel, django, android native, vuejs, react, embedded linux, typescript

0개의 댓글