[코드트리 챌린지] 객체_기본개념

HKTUOHA·2023년 9월 27일
0

코드트리

목록 보기
4/15
post-thumbnail

⭐실력진단 결과



구조체(클래스)를 선언하고 사용하는 방법에 대해 배우게 됩니다.

🟢007

✏️Class

  • __init__ : 클래스의 형태를 정의하는 생성자(constructor) 함수
    첫 번째 인자는 항상 self이며, 클래스를 지칭
  • kor, eng, math : 클래스가 선언될 때마다 값이 대입되는 멤버 변수
class Student:
	def __init__(self, kor, eng, math): 
    	self.kor = kor
        self.eng = eng
        self.math = math
  • lee 객체는 kor, eng, math라는 이름의 멤버 변수를 갖으며, 객체이름.멤버변수이름 형태로 값을 조회
  • 멤버 변수 이름을 k, e, m으로 정의했다면, 객체 생성 후 lee.k, lee.e, lee.m으로 값을 조회
lee = Student(90, 100, 80)  # 객체(instance) 생성
print(lee.kor)   # 90
print(lee.eng)   # 100
print(lee.math)  # 80

✏️Tuple

  • 파이썬에서는 class를 만들지 않고 tuple로 형태를 만들 수 있다.

튜플 언패킹(Tuple Unpacking)

  • 하나의 함수로 여러개의 반환값을 가지게 할 수 있거나 그것을 각각의 변수에 할당하는 방법
def num():
	return 1, 2
a, b = num()        # a, b = (1, 2) 와 같다
print(a, b, a + b)  # 1 2 3
  • 변수 이름을 사용하면 각 값이 의미하는 것을 알 수 있기 때문에 가독성을 높일 수 있다.
lee = (90, 100, 80)
k, e, m = lee
print(k, e, m)  # 90 100 80

튜플 패킹(Tuple Packing)

  • 여러개의 값을 하나의 변수에 넣는 방법
nums = 1, 2, 3, 4, 5
print(nums)  # (1, 2, 3, 4, 5)

📌문제


📌나의 코드

Runtime: 72ms, Memory: 29MB

# 클래스 선언
class meet:
    def __init__(self, code, location, time):
        self.code = code
        self.location = location
        self.time = time

# 변수 선언 및 입력
c, l, t = tuple(input().split())

# 객체 생성
ans = meet(c, l, t)

print(f"secret code : {ans.code}")
print(f"meeting point : {ans.location}")
print(f"time : {ans.time}")

''' Runtime: 102ms, Memory: 29MB
print("secret code :", ans.code)         
print("meeting point :", ans.location)
print("time :", ans.time)
'''



🟢Next Level

✏️객체 생성 및 값 변경

class를 통한 값 변경

  • 초기값을 설정하면 값을 넣어주지 않아도 객체 생성 가능
class Student:
	def __init__(self, kor=0, eng=0, math=0): 
    	self.kor = kor
        self.eng = eng
        self.math = math
  • 객체이름.매개변수이름 = 바꿀 값으로 객체에 저장된 값 변경 가능
kim = Student() 
print(kim.kor)   # 0
print(kim.eng)   # 0
print(kim.math)  # 0

kim.kor = 90
kim.eng = 80
kim.math = 100

print(kim.kor)   # 90
print(kim.eng)   # 80
print(kim.math)  # 100

tuple를 통한 값 변경

  • tuple은 class와 다른 게 기본값이라는 개념이 없으므로 적절한 초기값을 직접 넣어 생성
kim = (0, 0, 0)
k, e, m = kim
print(k, e, m)  # 0 0 0
  • tuple은 값을 변경할 수 없으므로 새로운 tuple을 생성해야 한다.
kim = (0, 0, 0)
k, e, m = kim
print(k, e, m)  # 0 0 0

kim = (k, e, 100)
k, e, m = kim
print(k, e, m)  # 0 0 100
  • tuple unpacking 시 값이 필요 없는 곳에 _를 넣어 사용하지 않을 수 있다.
kim = (90, 80, 100)
_, _, m = kim
print(m)  # 100

📌문제


📌나의 코드

class User:
    def __init__(self, id = "codetree", level = "10"):
        self.id = id
        self.lv = level
    
input_id, input_lv = tuple(input().split())

user1 = User()
user2 = User(input_id, input_lv)

print(f'user {user1.id} lv {user1.lv}')
print(f'user {user2.id} lv {user2.lv}')



🟢코드네임

✏️객체를 원소로 하는 리스트

class를 이용한 객체 리스트

  • 5개의 객체 생성 방법
class Student:
	def __init__(self, kor=0, eng=0, math=0): 
    	self.kor = kor
        self.eng = eng
        self.math = math        
  1. for 문
students = []
for _ in range(5):
	students.append(Student())
  1. list comprehension
students = [Student() for _ in range(5)]

입력을 받는 경우

  • class 이용
students = []
for _ in range(5):
	kor, eng, math = tuple(map(int, input().split()))
    students.append(Student(kor, eng, math))
    
student2 = students[1]
print(student2.kor, student2.eng, student2.math)
  • tuple 이용
students = [tuple(map(int, input().split())) for _ in range(5)]

student2 = students[1]
kor, eng, math = student2
print(kor, eng, math)

📌문제


📌나의 코드

class Agent:
    def __init__(self, codename, score):
        self.codename = codename
        self.score = score

agents = []
for _ in range(5):
    codename, score = input().split()
    score = int(score)
    agents.append(Agent(codename, score))

min_value = 10e9
for agent in agents:
    if min_value > agent.score:
        min_value = agent.score
        ans = agent

print(ans.codename, ans.score)
profile
공부 기록

0개의 댓글