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

python) use to isinstance

by kiseno 2024. 11. 12.
728x90
반응형
SMALL
class Student:
    def Study(self):
        print("print out study")

class Teacher:
    def Teach(self):
        print("teach to student")

classroom = [Student(), Student(), Teacher(), Student(), Student()]

[person.Study() if isinstance(person, Student) else person.Teach() for person in classroom]

### Class and Method Definitions

1. **`class Student:`** Defines a class named `Student`.

2. **`def Study(self):`** Inside the `Student` class, defines a method named `Study` that prints a message. The `self` parameter is a reference to the current instance of the class, which is a common practice in Python class methods.

   - **`print("print out study")`**: When the `Study` method is called, it prints the string `"print out study"` to the console.

3. **`class Teacher:`** Defines another class named `Teacher`.

4. **`def Teach(self):`** Inside the `Teacher` class, defines a method named `Teach` that prints a message. Like `Study`, `Teach` also uses the `self` parameter to reference the current instance.

   - **`print("teach to student")`**: When the `Teach` method is called, it prints the string `"teach to student"` to the console.

### Creating Instances and Executing Methods

5. **`classroom = [Student(), Student(), Teacher(), Student(), Student()]`**: This line creates a list named `classroom` that contains instances of `Student` and `Teacher`. The list is a mix of these instances, simulating a real classroom environment where both students and a teacher are present.

### List Comprehension with Conditional Execution

6. **`[person.Study() if isinstance(person, Student) else person.Teach() for person in classroom]`**: This is a list comprehension with a conditional expression that iterates over each `person` in the `classroom` list. For each `person`:

   - If the `person` is an instance of the `Student` class (checked using `isinstance(person, Student)`), it calls the `Study()` method of that `Student` instance, which prints `"print out study"`.
   
   - If the `person` is not an instance of the `Student` class (implying it's an instance of the `Teacher` class in this context), it calls the `Teach()` method of that `Teacher` instance, which prints `"teach to student"`.

This code demonstrates object-oriented programming principles such as class definition and instantiation, method definition and calling, as well as Python-specific features like list comprehensions and the `isinstance` function for type checking. The final line, in particular, showcases a practical application of polymorphism where an action is determined by the type of the object.

728x90
반응형
LIST