파이썬 내장 함수 및 클래스 활용

파이썬은 다양한 내장 함수와 클래스를 제공하여 개발자가 효율적으로 코드를 작성할 수 있도록 돕습니다. 아래에서는 주요 내장 함수와 클래스의 사용법을 설명합니다.

수치 처리 관련 함수

abs() 함수는 숫자의 절대값을 반환합니다. 정수나 실수뿐만 아니라 복소수에 대해서도 크기를 계산하여 반환합니다.

print(abs(-5))      # 출력: 5
print(abs(3.14))    # 출력: 3.14
print(abs(3+4j))    # 출력: 5.0

bin() 함수는 정수를 이진수 문자열로 변환합니다. 결과는 파이썬 표현식으로 사용 가능한 형식입니다.

print(bin(10))      # 출력: '0b1010'
print(bin(255))     # 출력: '0b11111111'

반복 가능 객체 검사 함수

all() 함수는 반복 가능 객체의 모든 요소가 참이면 True를 반환하며, 빈 객체일 경우에도 True를 반환합니다.

print(all([1, 2, 3]))   # 출력: True
print(all([0, 1, 2]))   # 출력: False
print(all([]))          # 출력: True

any() 함수는 반복 가능 객체 중 하나라도 참이면 True를 반환하고, 빈 객체이거나 모두 거짓일 경우 False를 반환합니다.

print(any([0, 0, 1]))   # 출력: True
print(any([0, 0, 0]))   # 출력: False
print(any([]))          # 출력: False

문자열 및 객체 표현 함수

ascii() 함수는 객체의 인쇄 가능한 표현을 문자열로 반환하나, ASCII가 아닌 문자는 이스케이프 시퀀스로 변환합니다.

print(ascii('안녕'))    # 출력: "'\\uc548\\ub155'"
print(repr('안녕'))     # 출력: "'안녕'"

dir() 함수는 인자가 없을 때는 현재 지역 스코프의 이름 목록을 반환하고, 객체가 주어지면 해당 객체의 유효한 속성 목록을 반환합니다.

print(dir())            # 현재 스코프 변수 목록
class Sample:
    def __init__(self):
        self.value = 10
print(dir(Sample()))    # Sample 인스턴스의 속성 목록

객체 타입 및 속성 조작

isinstance() 함수는 객체가 지정된 클래스의 인스턴스인지 확인합니다. 두 번째 인자로 튜플을 전달하면 여러 타입 중 하나라도 일치하면 True를 반환합니다.

print(isinstance(5, int))           # 출력: True
print(isinstance(5, (int, str)))    # 출력: True
print(isinstance("text", int))      # 출력: False

속성 존재 여부를 확인하기 위해 hasattr(), 값을 가져오기 위해 getattr(), 값을 설정하기 위해 setattr() 함수를 사용합니다.

class TestObj:
    def __init__(self):
        self.name = "test"

obj = TestObj()
print(hasattr(obj, 'name'))         # 출력: True
print(getattr(obj, 'name'))         # 출력: test
setattr(obj, 'value', 100)
print(obj.value)                    # 출력: 100

매핑 및 딕셔너리 생성

map() 함수는 반복 가능 객체의 각 항목에 함수를 적용한 결과를 이터레이터로 반환합니다.

numbers = [1, 2, 3, 4]
squared = map(lambda x: x**2, numbers)
print(list(squared))                # 출력: [1, 4, 9, 16]

dict() 클래스는 새로운 딕셔너리를 생성합니다. 다양한 방식으로 딕셔너리를 초기화할 수 있습니다.

d1 = dict()                         # 빈 딕셔너리
d2 = dict(a=1, b=2)                 # 키워드 인자
d3 = dict([('x', 10), ('y', 20)])   # 키-값 쌍 리스트
print(d2)                           # 출력: {'a': 1, 'b': 2}

클래스 및 타입 동적 생성

type() 함수는 하나의 인자로 호출되면 객체의 타입을 반환하고, 세 개의 인자로 호출되면 새로운 클래스를 동적으로 생성합니다.

# 타입 확인
print(type(123))                    # 출력: <class 'int'>

# 동적 클래스 생성
def greet(self, name="World"):
    print(f"Hello, {name}!")

DynamicClass = type('DynamicClass', (object,), {
    '__init__': lambda self: setattr(self, 'message', 'Created dynamically'),
    'greet': greet
})

instance = DynamicClass()
instance.greet("Python")            # 출력: Hello, Python!

속성 관리 및 프로퍼티

property() 클래스는 속성에 대한 getter, setter, deleter 메서드를 정의할 수 있게 해줍니다.

class Temperature:
    def __init__(self):
        self._celsius = 0
    
    @property
    def celsius(self):
        """섭씨 온도"""
        return self._celsius
    
    @celsius.setter
    def celsius(self, value):
        if value < -273.15:
            raise ValueError("절대 영하보다 낮을 수 없습니다")
        self._celsius = value
    
    @celsius.deleter
    def celsius(self):
        del self._celsius

temp = Temperature()
temp.celsius = 25
print(temp.celsius)                 # 출력: 25

호출 가능성 검사

callable() 함수는 객체가 호출 가능하면 True를 반환합니다. 함수, 메서드, 클래스 등이 호출 가능 객체입니다.

def sample_func():
    pass

class SampleClass:
    def __call__(self):
        pass

print(callable(sample_func))        # 출력: True
print(callable(SampleClass()))      # 출력: False
print(callable(SampleClass))        # 출력: True
sc = SampleClass()
print(callable(sc))                 # 출력: True (호출 연산자 구현)

상위 클래스 메서드 호출

super() 함수는 상위 클래스의 메서드를 호출할 때 사용됩니다. 특히 다중 상속에서 메서드 결정 순서(MRO)를 따릅니다.

class Parent:
    def greet(self):
        return "Hello from Parent"

class Child(Parent):
    def greet(self):
        parent_greeting = super().greet()
        return f"{parent_greeting} and Child"

child = Child()
print(child.greet())                # 출력: Hello from Parent and Child

태그: python built-in-functions Class type property

7월 26일 10:45에 게시됨