- Ball 클래스(터틀 그래픽) from turtle import * class Ball(Turtle): def __init__(self, color, speed, size): self.turtle = Turtle() self.turtle.shape("circle") self.x = 0 self.y = 0 self.color = color self.turtle.color(color, color) self.xspeed = speed self.yspeed = speed self.size = size def move(self): self.x += self.xspeed self.y += self.yspeed self.turtle.goto(self.x, self.y) ball = Ball("red", 1, 2)..
__str__() 메소드 - 객체의 데이터를 문자열로 변환할 때 사용 - print(인스턴스) 출력할 때 자동적으로 호출됨 class Car: def __init__(self, speed, color, model): self.speed = speed self.color = color self.model = model def drive(self): self.speed = 60 def __str__(self): msg = "속도 = "+str(self.speed)+" 색상 = "+self.color+" 모델 = "+self.model return msg myCar = Car(0, "red", "SUV") print(myCar) # 속도 = 0 색상 = red 모델 = SUV - 참고로 __str__() 메소..
객체 - 객체는 속성(변수)과 동작(메소드)을 가진 하나로 묶음 객체 = 변수 + 함수(메소드) 객체 생성 1. 클래스(객체의 설계도) 정의 : 객체가 가지고 있는 속성을 변수로 표현, 객체의 동작은 메소드로 정의 class 클래스이름: # 변수 생성 # 메소드 정의 class Car: # Car라는 이름의 클래스 생성 def drive(self): # drive 메소드 생성 self.speed = 10 2. 객체 생성 인스턴스 = 클래스() myCar = Car() 3. 속성(변수) 추가 인스턴스.속성 = 값 myCar.speed = 0 myCar.color = "red" myCar.model = "SUV" 4. 객체의 속성과 메소드 사용 print("자동차의 속도는",myCar.speed) # 자동차..
- 파일에서 단어 읽기 infile = open("C:\\Users\\Desktop\\happy.txt", "r") for line in infile: line = line.rstrip() word_list = line.split() for word in word_list: print(word) infile.close() - 파일 복사 infilename = input("기존 파일 이름: ") outfilename = input("복사된 파일 이름: ") infile = open(infilename, "r") outfile = open(outfilename, "w") s = infile.read() outfile.write(s) infile.close() outfile.close() shutil 모듈 사..
pickle 모듈 - 프로그램 상에서 우리가 사용하고 있는 객체를 파일 형태로 저장하기 위해 필요한 모듈 - pickle을 사용하기 위해서는 항상 binary 타입 정의해야 함 dump() - 객체를 pickle 모듈로 압축 1. pickle 모듈 포함 2. 객체 생성 3. open() 함수 사용하여 "wb"(이진파일 쓰기) 모드로 파일 열기 4. dump() 함수 호출로 객체 전달 5. 파일 닫기 import pickle # 딕셔너리 gameOption = { "sound":8, "videoQuality":"HIGH", "money":10000, "weaponList":["gun", "missile", "knife"] } # 이진 파일 오픈 file = open("C:\\Users\\Desktop\\s..
- 편의점 재고 관리 items = {"커피음료":7, "펜":3, "종이컵":2, "우유":1, "콜라":4, "책":5} item = input("물건의 이름을 입력하시오: ") print(items[item]) - 영한 사전 dict = {} dict['one'] = '하나' dict['two'] = '둘' dict['three'] = '셋' word = input("단어를 입력하시오: ") print(dict[word]) - 입력받은 숫자들의 평균 numlist = [] sum = 0 for i in range(5): num = int(input("정수를 입력하시오: ")) numlist.append(num) sum += numlist[i] result = sum / len(numlist) pri..
내 블로그 - 관리자 홈 전환 |
Q
Q
|
---|---|
새 글 쓰기 |
W
W
|
글 수정 (권한 있는 경우) |
E
E
|
---|---|
댓글 영역으로 이동 |
C
C
|
이 페이지의 URL 복사 |
S
S
|
---|---|
맨 위로 이동 |
T
T
|
티스토리 홈 이동 |
H
H
|
단축키 안내 |
Shift + /
⇧ + /
|
* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.