프로그래밍 언어/Python
Python에서 여러 생성자를 갖는 깔끔하고 Pythonic 방법
Rateye
2021. 8. 26. 10:10
728x90
반응형
질문 : Python에서 여러 생성자를 갖는 깔끔하고 Pythonic 방법은 무엇입니까?
이것에 대한 확실한 답을 찾을 수 없습니다. 내가 아는 한, 파이썬 클래스에서 __init__
그렇다면이 문제를 어떻게 해결해야합니까?
number_of_holes
속성이있는 Cheese
라는 클래스가 있다고 가정합니다. 치즈 오브젝트를 만드는 두 가지 방법을 어떻게 가질 수 있습니까?
이 작업을 수행하는 한 가지 방법 만 생각할 수 있지만 이것은 투박해 보입니다.
class Cheese():
def __init__(self, num_holes = 0):
if (num_holes == 0):
# Randomize number_of_holes
else:
number_of_holes = num_holes
당신은 무엇을 말합니까? 다른 방법이 있습니까?
답변
실제로 None
은 "마법"값에 훨씬 더 좋습니다.
class Cheese():
def __init__(self, num_holes = None):
if num_holes is None:
...
이제 더 많은 매개 변수를 추가 할 수있는 완전한 자유를 원한다면 :
class Cheese():
def __init__(self, *args, **kwargs):
#args -- tuple of anonymous arguments
#kwargs -- dictionary of named arguments
self.num_holes = kwargs.get('num_holes',random_holes())
*args
및 **kwargs
의 개념을 더 잘 설명하려면 (실제로 이러한 이름을 변경할 수 있습니다) :
def f(*args, **kwargs):
print 'args: ', args, ' kwargs: ', kwargs
>>> f('a')
args: ('a',) kwargs: {}
>>> f(ar='a')
args: () kwargs: {'ar': 'a'}
>>> f(1,2,param=3)
args: (1, 2) kwargs: {'param': 3}
http://docs.python.org/reference/expressions.html#calls
출처 : https://stackoverflow.com/questions/682504/what-is-a-clean-pythonic-way-to-have-multiple-constructors-in-python
728x90
반응형