Blog Full Notice
back to main page
python에서 ‘@’ 의 역할
motivation: python에서 @ operator (descriptor)의 역할을 파헤쳐보자.
설명 출처: https://stackoverflow.com/a/6392768
0. class method/field에 underscore 한개와 두개의 차이
출처: https://stackoverflow.com/a/1301409
_foo: Only a convention. A way for the programmer to indicate that the variable is private (whatever that means in Python).__foo: This has real meaning. The interpreter replaces this name with_classname__fooas a way to ensure that the name will not overlap with a similar name in another class.__foo__: Only a convention. A way for the Python system to use names that won’t conflict with user names.
1. descriptor를 함수에 쓰는 경우
def start_end(func):
def wrapper():
print("start")
func()
print("end")
return
return wrapper
@start_end
def any_func():
print("anything")
any_func() # 를 하게 되면 wrapper 함수가 출력이 된다.
2. descriptor를 class에 쓰는 경우
1. @property –> getter, setter, deleter를 편하게 쓰기 위해서 아래와 같은 형식으로 쓴다.
class Circle:
def __init__(self, radius):
self._radius = radius
@property # getter에 이거를 쓴다.
def radius(self):
return self._radius
@radius.setter
def radius(self, value):
self._radius = value
@radius.deleter
def radius(self):
del self._radius
이런 식으로 정의를 하게 되면,
c = Circle(5)
c.radius
c.radius = 1
del c.radius
만 해도 get, set, delete 가 가능하다. 여기서 delete는 아예 class field가 없어지게 된다. 메모리 allocation이 없어지는 것이 아니라.
2. @classmethod –> self.변수가 아니라 공유하는 그냥 변수들에 대해서, 즉 ‘methods that bound to class’를 정의하고자 할 때, 쓴다. ‘methods that bounds to class instance’가 아니고.
class Example:
_count = 0
def __init__(self):
Example._count += 1
@classmethod
def get_count(cls):
return cls._count
# Usage
e1 = Example()
e2 = Example()
print(Example.get_count()) # 2
3. @staticmethod –> class instance와 아무 상관없는 method를 쓸 때, @staticmethod를 쓴다.
class Math:
@staticmethod
def add(x, y):
return x + y
# Usage
print(Math.add(5, 7)) # 12
댓글남기기