반응형

Python decorator class와 type 메모는 함수형 decorator, 클래스형 decorator, class 객체의 생성 방식을 함께 보는 글이다.

decorator는 호출 대상을 감싸 동작을 바꾸는 패턴이고, class와 type 개념은 Python에서 클래스 자체도 객체라는 점을 이해하는 데 필요하다.

 

핵심 정리

decorator를 함수로 만들 수도 있고 클래스로 만들 수도 있다. 클래스형 decorator는 상태를 보관하거나 호출 전후 동작을 구조화할 때 유용하며, Python의 class와 type 개념을 함께 보면 decorator가 무엇을 감싸고 반환하는지 더 분명해진다.

  • decorator는 기존 함수나 클래스를 감싸 새 동작을 추가한다.
  • 클래스형 decorator는 인스턴스 상태를 보관하면서 호출 동작을 제어할 수 있다.
  • Python에서 class는 객체이고 type은 클래스 생성과 관계된 핵심 개념이다.
  • decorator를 읽을 때는 입력으로 무엇을 받고 무엇을 반환하는지 확인해야 한다.
  • metaclass와 decorator는 모두 객체 생성과 동작 변경을 다루지만 적용 지점이 다르다.

decorator 코드는 문법보다 호출 흐름을 따라가야 한다. 감싸는 대상, 반환되는 객체, 실제 호출 시점이 핵심이다.

이어서 볼 글

 

class, type

http://blog.ionelmc.ro/2015/02/09/understanding-python-metaclasses/#types-vs-classes

> in python2

> types (classes implemented in C)

> classes (implemented in pure Python)

>

> in Python 3 class and type mean the same thing.

> A class is an object, and just like any other object,

> it's an instance of something: a metaclass. The default metaclass is type.

> 그래?

> 그러네.. isinstance(클래스명, type) 하면 True 나온다.

> 클래스도 인스턴스라는거네.. 재밌네

x.__class__

type(x)


>>> type(3)
<type 'int'>
>>> type('a')
<type 'str'>
>>> type([1,2,3])
<type 'list'>
>>>

<type 'list'>
>>> 3.__class__
  File "<stdin>", line 1
    3.__class__
              ^
SyntaxError: invalid syntax
>>> 'a'.__class__
<type 'str'>
>>> [1,2,3].__class__
<type 'list'>
>>>

아래는 내가 해본건데 신기하네.. instance랑 아닌거랑 type 또는 __class__의 결과가 다르군


class Foo(object):
    pass

f = Foo()

print Foo.__class__
print type(Foo)

print f.__class__
print type(f)

결과
<type 'type'>
<type 'type'>
<class '__main__.Foo'>
<class '__main__.Foo'>

반응형

+ Recent posts