냠냠쿠 2024. 4. 30. 20:28
728x90

1. 객체 만들기 

1) 객체만들기 

students = [
    { "name":"홍길동", "korean": 87, "math": 80 },
    { "name":"김길동", "korean": 50, "math": 80 },    
    { "name":"이길동", "korean": 14, "math": 54 },            
]

print("이름","총점","평균",sep="\t")

for student in students:
    score_sum = student["korean"] + student["math"]
    score_avg = score_sum/2
      

    print(student["name"], score_sum, score_avg, sep="\t")

 

 

2) 딕셔너리를 만들기

def create_student(name, korean, math):
    return {
        "name" : name,
        "korean" : korean,
        "math" : math
    }

students = [
    { "name":"홍길동", "korean": 87, "math": 80 },
    { "name":"김길동", "korean": 50, "math": 80 },    
    { "name":"이길동", "korean": 14, "math": 54 },            
]


print("이름","총점","평균",sep="\t")

for student in students:
    score_sum = student["korean"] + student["math"]
    score_avg = score_sum/2
    
    print(student["name"], score_sum, score_avg, sep="\t")

 

3) 코드를 더 분리시키기

def create_student(name, korean, math):
    return {
        "name" : name,
        "korean" : korean,
        "math" : math
    }

def student_get_sum(student):
    return student["korean"] + + student["math"]

def student_get_avg(student):
    return student_get_sum(student)/2

def student_to_string(student):
    return "{}\t{}\t{}".format(
        student["name"],
        student_get_sum(student),
        student_get_avg(student)
    )

students = [
    { "name":"홍길동", "korean": 87, "math": 80 },
    { "name":"김길동", "korean": 50, "math": 80 },    
    { "name":"이길동", "korean": 14, "math": 54 },            
]


print("이름","총점","평균",sep="\t")

for student in students:
    score_sum = student["korean"] + student["math"]
    score_avg = score_sum/2
    
    print(student["name"], score_sum, score_avg, sep="\t")

 

 

2. 클래스 선언하기

class 클래스이름:
    클래스 내용

 

아래와 같이 만들어진 객체를 인스턴스라고 부른다.

인스턴스 이름(변수이름) = 클래스이름()

 

 

3. 생성자

- 클래스 이름과 같은 함수

class 클래스이름:
    def __init__ (self, 추가 매개변수):
        pass

 

class Student:
    def __init__(self, name, korean, math):
        self.name = name
        self.korean = korean
        self.math = math

students = [
    { "name":"홍길동", "korean": 87, "math": 80 },
    { "name":"김길동", "korean": 50, "math": 80 },    
    { "name":"이길동", "korean": 14, "math": 54 },            
]

student[0].name
student[0].korean
student[0].math

 

 

4. 메서드

클래스가 가지고 있는 함수

class 클래스이름:
    def 메서드이름(self, 추가매개변수):
        pass

 

728x90