Python3 중급 주제

2024. 1. 24. 18:12python/intermediate

  1. 클래스

다른 모든 객체 지향 프로그래밍 언어와 마찬가지로 Python은 클래스를 지원합니다. Python 클래스에 대한 몇 가지 사항을 살펴보겠습니다.

  • 클래스는 class 키워드로 생성됩니다 .
  • 속성은 클래스에 속하는 변수입니다.
  • 속성은 항상 공개되며 점(.) 연산자를 사용하여 액세스할 수 있습니다. 예: Myclass.Myattribute

예를 들어 수업에 대한 샘플은 다음과 같습니다.

In [ ]:
# creates a class named MyClass 
class MyClass:   
        # assign the values to the MyClass attributes 
        number = 0       
        name = "noname"
  
def Main(): 
        # Creating an object of the MyClass.  
        # Here, 'me' is the object 
        me = MyClass()  
  
        # Accessing the attributes of MyClass 
        # using the dot(.) operator    
        me.number = 1337    
        me.name = "숫자"
  
        # str is an build-in function that  
        # creates an string 
        print(me.name + " " + str(me.number)) 
     
# telling python that there is main in the program. 
if __name__=='__main__':   
        Main()
  1. 메소드

메소드는 Python 코드에서 특정 작업을 수행하기 위한 코드 묶음입니다.

  • 클래스에 속하는 함수를 메소드(Method)라고 합니다.
  • 모든 메소드에는 'self' 매개변수가 필요합니다. 다른 OOP 언어로 코딩했다면 'self'를 현재 객체에 사용되는 'this' 키워드로 생각할 수 있습니다. 현재 인스턴스 변수를 숨김 해제합니다. 'self'는 대부분 'this'처럼 작동합니다.
  • 'def' 키워드는 새로운 메소드를 생성하는 데 사용됩니다.
In [ ]:
# A Python program to demonstrate working of class 
# methods 
  
class Vector2D: 
        x = 0.0
        y = 0.0
  
        # Creating a method named Set 
        def Set(self, x, y):      
                self.x = x 
                self.y = y 
  
def Main(): 
        # vec is an object of class Vector2D 
        vec = Vector2D()    
         
        # Passing values to the function Set 
        # by using dot(.) operator. 
        vec.Set(5, 6)        
        print("X: " + str(vec.x) + ", Y: " + str(vec.y)) 
  
if __name__=='__main__': 
        Main() 

3. 상속

상속은 특정 클래스가 기본 클래스로부터 기능을 상속하는 방식으로 정의됩니다. 기본 클래스는 '슈퍼클래스'라고도 하며, 슈퍼클래스에서 상속받는 클래스는 '하위클래스'라고도 합니다.

그림에 표시된 것처럼 Derived 클래스는 기본 클래스에서 기능을 상속할 수 있으며 자체 기능을 정의할 수도 있습니다

# Syntax for inheritance

class derived-classname(superclass-name)

In [ ]:
# A Python program to demonstrate working of inheritance 
class Pet: 
        #__init__ is an constructor in Python 
        def __init__(self, name, age):      
                self.name = name 
                self.age = age 
  
# Class Cat inheriting from the class Pet 
class Cat(Pet):          
        def __init__(self, name, age): 
                # calling the super-class function __init__  
                # using the super() function 
                super().__init__(name, age)  
  
def Main(): 
        thePet = Pet("Pet", 1) 
        jess = Cat("Jess", 3) 
          
        # isinstance() function to check whether a class is  
        # inherited from another class 
        print("Is jess a cat? " +str(isinstance(jess, Cat))) 
        print("Is jess a pet? " +str(isinstance(jess, Pet))) 
        print("Is the pet a cat? "+str(isinstance(thePet, Cat))) 
        print("Is thePet a Pet? " +str(isinstance(thePet, Pet))) 
        print(jess.name) 
  
if __name__=='__main__': 
        Main() 
  1. 반복자

반복자는 반복될 수 있는 객체입니다.

  • Python은 iter() 메서드를 사용하여 클래스의 반복자 객체를 반환합니다.
  • 그런 다음 반복자 객체는 next() 메서드를 사용하여 다음 항목을 가져옵니다.
  • StopIteration 예외가 발생하면 for 루프가 중지됩니다.
In [ ]:
# This program will reverse the string that is passed 
# to it from the main function 
class Reverse: 
    def __init__(self, data): 
        self.data = data 
        self.index = len(data)         
  
    def __iter__(self): 
        return self
      
    def __next__(self): 
        if self.index == 0: 
            raise StopIteration     
        self.index-= 1
        return self.data[self.index] 
  
def Main(): 
    rev = Reverse('Drapsicle') 
    for char in rev: 
        print(char) 
  
if __name__=='__main__': 
    Main() 
  1. 발전기
  • 반복자를 만드는 또 다른 방법입니다.
  • 별도의 클래스가 아닌 함수를 사용합니다.
  • next() 및 iter() 메서드에 대한 배경 코드를 생성합니다.
  • 생성기의 상태를 저장하고 next()가 다시 호출될 때 재개 지점을 설정하는 Yield라는 특수 문을 사용합니다.
In [ ]:
# A Python program to demonstrate working of Generators 
def Reverse(data): 
    # this is like counting from 100 to 1 by taking one(-1)  
    # step backward. 
    for index in range(len(data)-1, -1, -1): 
        yield data[index] 
  
def Main(): 
    rev = Reverse('숫자') 
    for char in rev: 
        print(char) 
    data ='숫자'
    print(list(data[i] for i in range(len(data)-1, -1, -1))) 
  
if __name__=="__main__": 
    Main() 
 
출처 : https://www.geeksforgeeks.org/python3-intermediate-level-topics/

'python > intermediate' 카테고리의 다른 글

Python의 선형 회귀 II  (1) 2024.01.26
Python의 선형 회귀 I  (1) 2024.01.25
프롬프트 엔지니어링 실제 사례  (1) 2024.01.23
상속과 구성 Python OOP 가이드  (1) 2024.01.22
python-for-data-analysis-II  (0) 2024.01.21