파이썬에서 클래스를 확장하는 방법은 무엇입니까?
파이썬에서 어떻게 클래스를 확장 할 수 있습니까? 예를 들어 내가 가지고 있다면
color.py
class Color:
def __init__(self, color):
self.color = color
def getcolor(self):
return self.color
color_extended.py
import Color
class Color:
def getcolor(self):
return self.color + " extended!"
하지만 이것은 작동하지 않습니다.에서 작업 color_extended.py
하면 색상 객체를 만들고 getcolor
함수를 사용할 때 "extended!"라는 문자열이있는 객체를 반환 할 것으로 예상합니다. 결국. 또한 가져 오기에서 초기화를 가져 왔어 야합니다.
파이썬 3.1 가정
감사
사용하다:
import color
class Color(color.Color):
...
이 파이썬 2.x에서 인 경우에, 당신은 또한 유도 할 것이다 color.Color
에서 object
그것을 만들기 위해, 새로운 스타일의 클래스 :
class Color(object):
...
Python 3.x에서는 필요하지 않습니다.
내장 클래스를 포함하여 클래스를 확장하는 또 다른 방법 (특히 의미, 새 메소드 추가, 기존 메소드 추가)은 Python 자체의 범위를 벗어나 확장하는 기능을 추가하는 전처리기를 사용하여 확장을 다음으로 변환하는 것입니다. 파이썬이 실제로 그것을보기 전에 일반적인 파이썬 구문.
str()
예를 들어 Python 2의 클래스 를 확장하기 위해이 작업을 수행했습니다 . str()
때문에 같은 인용 데이터에 내재 결합의 특히 흥미로운 대상 'this'
과 'that'
.
다음은 일부 확장 코드입니다. 여기서 추가 된 유일한 비 Python 구문은 extend:testDottedQuad
비트입니다.
extend:testDottedQuad
def testDottedQuad(strObject):
if not isinstance(strObject, basestring): return False
listStrings = strObject.split('.')
if len(listStrings) != 4: return False
for strNum in listStrings:
try: val = int(strNum)
except: return False
if val < 0: return False
if val > 255: return False
return True
그 후 전처리기에 공급되는 코드를 작성할 수 있습니다.
if '192.168.1.100'.testDottedQuad():
doSomething()
dq = '216.126.621.5'
if not dq.testDottedQuad():
throwWarning();
dqt = ''.join(['127','.','0','.','0','.','1']).testDottedQuad()
if dqt:
print 'well, that was fun'
전처리 기가 그걸 먹고, 몽키 패칭없이 일반 파이썬을 뱉어 내고, 파이썬은 제가 의도 한대로합니다.
Just as a c preprocessor adds functionality to c, so too can a Python preprocessor add functionality to Python.
My preprocessor implementation is too large for a stack overflow answer, but for those who might be interested, it is here on GitHub.
참고URL : https://stackoverflow.com/questions/15526858/how-to-extend-a-class-in-python
'code' 카테고리의 다른 글
id = 1-id 원자입니까? (0) | 2020.10.22 |
---|---|
JPA : @JoinColumn과 @PrimaryKeyJoinColumn의 차이점은 무엇입니까? (0) | 2020.10.22 |
Android 뷰 수명주기 (상태 다이어그램)를 그래픽으로 표현한 것이 있습니까? (0) | 2020.10.22 |
Android 스튜디오에는 어떤 JDK 버전 (언어 수준)이 필요합니까? (0) | 2020.10.22 |
수은의 모범 사례 : 분기 대 복제, 부분 병합? (0) | 2020.10.22 |