더 좋은 제목이 없기 때문에 지금까지 제가 가지고있는 것입니다.`int`를 상속받은 클래스는 변수 할당과 같은 이상한 유령이됩니다.
예상대로class cordinate(int):
def __new__(self, *args, **kwargs):
self.x = args[0]
self.y = args[1]
## Try to get pixel [0,0] and see what it got:
if self.x == 0 and self.y == 0:
print('New Here')
print(self.x, self.y, self.angle, self.distance_from_edge)
self.angle = 225
self.distance_from_edge = 13
args = [self.distance_from_edge,]
return super(cordinate, self).__new__(self, *args, **kwargs)
cordinates = [cordinate(0,0), cordinate(2,10), cordinate(3,8)]
는,이 코드는 오류 발생 :
if self.x == 2 and self.y == 10:
이 코드의 출력 : :
New Here
2 10 225 13
New Here
Traceback (most recent call last):
File "test.py", line 17, in <module>
cordinates = [cordinate(0,0), cordinate(2,10), cordinate(3,8)]
File "test.py", line 9, in __new__
print(self.x, self.y, self.angle, self.distance_from_edge)
AttributeError: type object 'cordinate' has no attribute 'angle'
어떤 이유를, 나는 다음과 같은 시도
이제 시뮬레이션이 있다고 확신합니다. 이것에 대한 설명과 공포에 대한 필요성이나 귀신을 믿기 시작하는 것이 아닙니다. ..
그러나 나는 그걸 가지고 놀았지만 감각이 없습니다. 이 행동에 대한 설명은 무엇입니까 - 이름이 있습니까? 어떻게 새로 생성 된 인스턴스가 2 행 아래에 설정 될 값을 가질 수 있습니까?
예상 값 : 항상 충돌 - 상단에 정의되지 않은 키가있는 인쇄물을 의도적으로 배치했기 때문에.
파이썬 : 3.5.1 (윈도우 8) 당신이 the data model documentation에서 볼 수 있듯이
__new__'이 ** 클래스 ** (종래'의 CLS입니다 '에 첫 번째 인수 '), 인스턴스가 아닙니다 (일반적으로'self'). 따라서 이러한 속성은 * first * 호출이 충돌하지 않는 한 이미 설정되어 있습니다. – jonrsharpe
@jonrsharpe 당신은 내 체인을 janking거야? 하하. 그것이 간단하다면 나는 생성시이 클래스에'x'와'y'를 어떻게 할당하는지 재평가해야 할 것입니다. – Torxed
관심 없어, '__init__'보다는'__new__'을 사용하는 이유가 있습니까? – Holloway