작년에 파이썬을 배웠고 새 프로젝트로 다시 돌아가고있었습니다. 나는 처음에 걸림돌을 때렸고, 문서를 뚫고 나서는 여전히 난처한 상황에 처해있다. 나는 그것이 단순한 무엇인가 믿어야한다. 그러나 나는 그것을 발견 할 수 없다.예기치 않게 인스턴스 속성이로드되었습니다.
내가 파일에 설정 한 다음 한 : 여기에 문제의 대화 형 프롬프트에서 다음
class Wrapper(object):
def __init__(self, title=None):
self.header = Thing("HEADER")
if title is not None:
self.header.content.append(Thing("TITLE", content=[str(title)]))
self.body = Thing("BODY")
self.content = Thing("COMPLETE", content=[self.header, self.body])
class Thing(object):
def __init__(self, name, content=[]):
self.name = name
self.content = content
내가 할 :
>>> import things
>>> a = things.Wrapper("This is a title")
을 지금, 나는 그 시점에서 기대 body
속성이 a
이면 "BODY"
이고 빈 목록으로 구성된 content
인 Thing
인스턴스가됩니다. 내가 궁금한 점은 그 content
이 실제로 "TITLE"
인스턴스가 들어있는 목록이며 a.header.content
이 들어 있다는 것입니다.
>>> a.header.name
'HEADER'
>>> a.header.content
[<test.Thing object at 0xb752290c>]
>>> a.body.name
'BODY'
>>> a.body.content
[<test.Thing object at 0xb752290c>]
>>> a.body.content[0].name
'TITLE'
>>> a.body.content[0].content
['This is a title']
나는 내 인생에 그런 식으로 할당 됐는지 a.body.content
알아낼 수 없기 때문. 누구든지 이것에 대해 밝힐 수 있습니까? 기본 인터프리터가 제 기능을 생성 할 때 디폴트 파라미터 번만 계산되는대로
이 답변/설명을 보시기 바랍니다 : [ "Python : Least Astonishment": 기본 가변 인수] (http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default- 인수) –