본문 바로가기
개념/혼자 공부하는 파이썬

python) class function

by kiseno 2024. 10. 25.
728x90
반응형
SMALL
class Student:
    count = 0
    students = []

    @classmethod
    def print(cls):
        print("========Student list========")
        print("name\tsum\taverage")
        for student in cls.students:
            print(str(student))
        print("-------- --------- --------")

    def __init__(self, name, korean, english, math, science):
        self.name = name
        self.korean = korean
        self.math = math
        self.english = english
        self.science = science
        self.count += 1
        Student.students.append(self)

    def get_sum(self):
        return self.korean + self.math + self.english + self.science

    def get_average(self):
        return self.get_sum() / 4

    def __str__(self):
        return "{}\t{}\t{}".format(self.name, self.get_sum(), self.get_average())

Student("윤인성", 87,98,88,95)
Student("연하진",92,98,96,98)
Student("구지연",98,96,90,89)
Student("나선주",88,86,64,87)
Student("윤아린",98,99,78,80)

Student.print()

This code snippet demonstrates an enhanced version of the `Student` class that tracks student instances and can print a summary of all students, including their name, total score, and average score. Here's a closer look at the structure and functionality:

### Enhanced `Student` Class Features

- **Class Attributes**:
  - `count`: Tracks the number of `Student` instances created. However, there's a minor mistake in the implementation; this attribute is not incremented in the `__init__` method. Instead, an instance attribute `self.count` is incremented, which does not affect the class attribute `Student.count`.
  - `students`: A class-level list that holds references to all `Student` instance objects.

- **Class Method `print`**:
  - Defined with the `@classmethod` decorator, allowing it to access class attributes and methods with the `cls` parameter, which represents the class itself. This method prints a summary of all student instances stored in the `students` list, displaying each student's name, total score, and average score.

- **`__init__` Method**:
  - Initializes each new instance of `Student` with name and scores in various subjects. It incorrectly attempts to increment `self.count` (an instance attribute) instead of `Student.count` (the correct class attribute) and adds the newly created instance to the `students` list.

- **Instance Methods**:
  - `get_sum`: Returns the sum of the scores.
  - `get_average`: Calculates the average score.
  - `__str__`: Returns a string representation of the student, formatted to include the name, total score, and average score, separated by tabs.

### Corrections and Enhancements

1. **Incrementing `count` Correctly**:
   To accurately track the total number of students, replace `self.count += 1` with `Student.count += 1` in the `__init__` method.

2. **Printing the Student List**:
   The class method `print` is well-implemented to iterate over the `students` list and print each student's information. However, the method name `print` could potentially lead to confusion with the built-in `print` function. Consider renaming this method to avoid naming conflicts (e.g., `print_students`).

### Corrected Version of `__init__`

def __init__(self, name, korean, english, math, science):
    self.name = name
    self.korean = korean
    self.math = math
    self.english = english
    self.science = science
    
    Student.count += 1  # Correct way to increment the class attribute
    Student.students.append(self)


```

### Usage

After defining the `Student` instances as shown in the code snippet, calling `Student.print()` (or `Student.print_students()` if renamed) will output a neatly formatted list of all students, their total scores, and their average scores.

This class effectively demonstrates object-oriented programming concepts such as class attributes, instance methods, class methods, and special methods like `__str__`. It showcases how to manage a collection of objects in Python, performing aggregations and reporting on the objects' state.

728x90
반응형
LIST