클래스 관련 기초적 질문..

39 views
Skip to first unread message

Pyrot

unread,
Nov 15, 2009, 7:34:24 AM11/15/09
to Python 3 질문 게시판
2.6 문법입니다만 아마 print만 바꿔주면 3.1과 다르지 않을것 같습니다^^
질문 2개입니다~


class rawDNA:
import string
// 여기에 둬야하는건가요...같은 파일에 있다면 클래스 선언 밖에 있어도
되죠?
//그런데 여기에 두면 클래스 선언 시에 임포트 되는건가요?
//클래스 인스턴스 생성시 임포트 된다면 모든 인스턴스를 다 종료(del?)
하면 임포트 된건 유지되나요?
trans = string.maketrans("GATC","CTAG")
def __init__(self, template = "GATTACA"):
self.template = template
def noncoding(self):
print template.translate(trans)
//제가 예상한 것은 이부분에서 작동이 되는 것입니다! 위의 __init__에서
외부에서 reference 받은 template 변수를
// 객체 내부의(self의) template으로 할당했으니 객체 내부에서도 참조
가 가능하게 되지 않을까 했던 것이었는데
//다음과 같은 에러와 함께 안되네요 ㅠ

Traceback (most recent call last):
File "<pyshell#29>", line 1, in <module>
test.noncoding()
File "<pyshell#25>", line 7, in noncoding
print template.translate(trans)
NameError: global name 'template' is not defined


global name 까지 찾는 다는 것은.. 객체 내부 scope에서 정의가 안되었다.. 이런 뜻이겠죠? 그런데 분명
__init__에서 한것 같은데..

다만

class rawDNA:
import string
trans = string.maketrans("GATC","CTAG")
def __init__(self, template = "GATTACA"):
self.template = template
def noncoding(self):
print self.template.translate(trans)

로 코딩하면 다시 되는 것입니다!!

음.. 이해가 안되네요 ㅠㅠ

again4you

unread,
Nov 15, 2009, 9:42:53 AM11/15/09
to Python 3 질문 게시판
안녕하세요 파이썬 3의 저자 우상정입니다.

우선 질문하신 예제의 noncoding() 메소드에서
클래스 멤버 변수에 접근하기 위해서는 반드시 self인자를 이용하셔야 합니다.

그렇지 않은 경우 전역 변수부터 이름을 검색하기 때문입니다.
저희 책에서 참고하실 부분은 "5.3 클래스 객체와 인스턴스 객체의 이름공간(p89)"를 보시면 됩니다.
5-3.1.py가 위의 문제와 동일한 예제입니다.

그래서 수정한 예제는 다음과 같습니다.

class rawDNA:
import string
trans = string.maketrans("GATC","CTAG")
def __init__(self, template = "GATTACA"):
self.template = template
def noncoding(self):

print self.template.translate(self.trans)

oRawDNA = rawDNA()
oRawDNA.noncoding()


그럼 오늘 하루도 즐거운 하루 보내시고,
즐거운 파이썬 프로그래밍하세요. 감사합니다.

Pyrot

unread,
Nov 17, 2009, 10:48:04 PM11/17/09
to Python 3 질문 게시판
감사합니다
Reply all
Reply to author
Forward
0 new messages