- 서로 관계 깊은 정보의 집합
- 정보를 조작하기 위한 일련의 연산
-
정보는 객체 안의 인스턴스 변수에 저장
-
메서드는 객체 안의 함수
-
인스턴스 변수와 메서드 -> 객체의 속성(attribute)
-
Example: Center
center / radius : instance variables
draw / move : methods
- 모든 객체는 어떤 클래스의 인스턴스
- 클래스 : 그 인스턴스가 무엇을 알고 있고, 어떤 일을 할 수 잇는지에 대한 설명.
-
Program Specification
-
Designing the Program
from math import sin, cos, radians def main(): angle = float(input("Enter the launch angle (in degrees): ")) vel = float(input("Enter the initial velocity (in meters/sec): ")) h0 = float(input("Enter the initial height (in meters): ")) time = float(input("Enter the time interval between position calculations: ")) theta = radians(angle) xpos = 0 ypos = h0 xvel = vel * cos(theta) yvel = vel * sin(theta) while ypos >= 0.0: xpos = xpos + time * xvel yvel1 = yvel - time * 9.8 ypos = ypos + time * (yvel + yvel1) / 2.0 yvel = yvel1 print("\nDistance traveled: {0:0.1f} meters.".format(xpos))
-
Modularizing the Program
def main(): angle, vel, h0, time = getInputs() cball = Projectile(angle, vel, h0) while cball.getY() >= 0: cball.update(time) print("\nDistance traveled: {0:0.1f} meters.".format(xpos))
class <class-name>
<method-definitions>- 메서드 정의는 일반적인 함수 정의와 동일하다.(클래스 정의 안에서 함수를 정의 할 경우 일반적인 독립된 함수가 아니라 그 클래스의 메서드가 됨)
- self : 인스턴스 변수를 통해 객체 안에 데이터를 저장. / 객체의 속성에 접근하는 용도로 사용
- "init" 객체를 생성하는 생성자 / 객체의 인스턴스 객체를 어떤 값으로 초기화
-
복잡한 실세계를 모형화 가능
-
객체 : 어떤 사람 / 사물에 대한 정보로 모아 놓는 용도로 많이 쓰인다.
-
Example: Student
class Student: def __init__(self, name, hours, qpoints): self.name = name self.hours = float(hours) self.qpoints = float(qpoints) def getName(self): return self.name def getHours(self): return self.hours def getQPoints(self): return self.qpoints def gpa(self): return self.qpoints/self.hours def makeStudent(infoStr): name, hours, qpoints = infoStr.split("\t") return Student(name, hours, qpoints) def main(): filename = input("Enter the name of the grade file: ") infile = open(filename, 'r') best = makeStudent(infile.readline()) for line in infile: s = makeStudent(line) if s.gpa() > best.gpa(): best = s infile.close() print("The best student is: ", best.getName()) print("hours: ", best.getHours()) print("GPA: ", best.gpa()) if __name__ == '__main__': main()
-
세부사항을 클래스 정의 안으로 숨기는 것
-
main() program : 객체가 어떤 일을 할 수 있는지만 알면 충분. 어떻게 하는지(구현)에 대해서는 신경 쓸 필요 없음 => 캡슐화(관심사의 분리)
-
객체의 인스턴스 변수는 클래스의 인터페이스를 통해서만 접근하고 수정할 수 있는 방법
-
구체적 구현 사항: 클래스 정의 안에 포장. 격리. 또 다른 형태의 추상화
-
장점 : 클래스를 사용하는 나머지 프로그램을 '망치는' 일 없이 클래스만 따
-
로 수정할 수 있다
-
모듈 문서화 - 독스트링(docstring)
# Projectile.py """이 모듈은 발사체의 운동을 모형화하는 간단한 클래스를 제공한다.""" import projectile print(projectile.Projectile.__doc__)
-
여러 모듈 : main() 프로그램에서 import 하는 방식
- GUI 설계 / 객체지향적 방식