ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Python tutorial] 16. Classes, Objects and Inheritance
    코딩/Python 2022. 12. 21. 17:16
    728x90

    Classes and Objects

    • OOP(Object Oriented Programming)언어: 속성과 메서드(명령, 함수)를 가지는 객체
    • 클래스: 객체를 생성하기 위한 기본청사진
    • 객체: 실제 사용되는 대상

    Create a Class: class

    class MyClass: # create a class 'MyClass'
      x = 5 # property
    
    p1 = MyClass() # create a object 'p1'
    
    print(MyClass) # <class '__main__.MyClass'>
    print(p1.x) # 5
    class Person:
      def __init__(self, name, age):
        self.name = name
        self.age = age
    
      def __str__(self):
        return f"{self.name}({self.age})"
    
      def myfunc(self): # object method
        print("Hello my name is " + self.name)
    
    p1 = Person("John", 36)
    
    print(p1.name) # John
    print(p1.age) # 36
    print(p1) # John(36)
    p1.myfunc() # Hello my name is John

    __init__() Function

    • 모든 클래스에게 필요
    • 클래스가 초기화될 때 항상 실행
    • 객체 속성에 값을 부여할 때
    • 객체를 생성할 때 꼭 수행해야 할 다른 절차가 있을 때 사용
    • 클래스로부터 객체가 생성될 때 자동으로 호출

    __str__() Function

    • 클래스 객체가 문자열로 표현될 때 반환되어야 하는 것을 제어
    • 설정되지 않은 경우 객체의 문자열 표현 반환

    self parameter

    • 클래스의 현재 인스턴스에 대한 참조
    • 클래스에 속하는 변수에 액세스하는 데 사용
    • 이름을 self 로 지정할 필요는 없음
    • 클래스에 있는 모든 함수의 첫 번째 매개변수

    Modify Object Properties

    p1.age = 40

    Delete Object or Properties: del

    # delete property
    del p1.age
    
    # delete object
    del p1

    pass Statement

    • 클래스 정의: 비워둘 수 없음
    • 내용이 없는 클래스 정의: 오류가 발생하지 않도록 pass 문 사용
    class Person:
      pass

    Inheritance

    Create a Parent Class

    class Person:
      def __init__(self, fname, lname):
        self.firstname = fname
        self.lastname = lname
    
      def printname(self):
        print(self.firstname, self.lastname)

    Create a Child Class

    class Student(Person): # class Person으로부터 새로운 클래스 Student 생성
      pass # Person 외의 추가 속성, 메서트 없을 경우
    
    x = Student("Mike", "Olsen")
    x.printname() # Mike Olsen

    Add the init() Function

    부모클래스의 속성 받지 않을 경우

    class Student(Person):
      def __init__(self, fname, lname):

    부모클래스의 속성만 상속

    class Student(Person):
      def __init__(self, fname, lname):
          Person.__init__(self, fname, lname)
    super(): 부모클래스로부터 모든 속성과 메서드 상속
    class Student(Person):
      def __init__(self, fname, lname, year):
        super().__init__(fname, lname)
        self.graduationyear = year
    
      def welcome(self):
        print("Welcome", self.firstname, self.lastname, "to the class of", self.graduationyear)
    
    x = Student("Mike", "Olsen", 2019)
    x.welcome()
    728x90

    '코딩 > Python' 카테고리의 다른 글

    [Python tutorial] 18. File handling  (0) 2022.12.21
    [Python tutorial] 17. Try...Except  (0) 2022.12.21
    [Python tutorial] 15. Lambda  (0) 2022.12.21
    [Python tutorial] 14. Functions  (0) 2022.12.21
    [Python tutorial] 13. Control flow, Loop, Iterator  (0) 2022.12.21

    댓글

Designed by Tistory.