파이썬 클래스 @property, @staticmethod, @classmethod

property

Jay
2 min readMar 19, 2019
  • 주로 인풋 벨리데이션에 사용 (Input Validation)
TRAP_ARTISTS = [
'Rick Ross',
'Future',
'Desiigner',
'Young Jeezy'
]
class TrapArtist:
def __init__(self, name):
self._name = name
@property
def name(self):
return self._name
@name.setter
def name(self, name):
if name not in TRAP_ARTISTS:
raise ValueError('%s is not a trap artist' % name)
self._name = name

staticmethod

  • 주로 생성자로 사용 (Factory Function)
import random...extended    @staticmethod
def random_artist():
return TrapArtist(random.choice(TRAP_ARTISTS))
ta = TrapArtist.random_artist()
print(ta.name)
# Future

classmethod

  • instance method (기본방식, self를 method 받는) 와 staticmethod (완전 분리된 방식) 의 중간이라고생각하면 된다.
  • 클래스로 인스턴스를 생성하는데, 인스턴스 메소드는 인스턴스 레벨에서 일어나는 일을 다루지만, 클래스 메소드는 인스턴스가 클래스의 것을 다룰 수 있다.
...extended    _hits = [
'Dead presidents',
'Panda',
'Money',
]

@classmethod
def hits(cls):
return cls._hits
print(TrapArtist.hits())# ['Dead presidents', 'Panda', 'Money']

참고문헌

--

--

Jay
Jay

Written by Jay

Brain Neural Network : Where neuroscience meets machine learning

Responses (1)