Files
python3-cookbook/cookbook/c09/p08_inclass_decorator.py

41 lines
962 B
Python
Raw Permalink Normal View History

2015-02-10 17:27:21 +08:00
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 类中定义装饰器
Desc :
"""
from functools import wraps
class A:
# Decorator as an instance method
def decorator1(self, func):
@wraps(func)
def wrapper(*args, **kwargs):
print('Decorator 1')
return func(*args, **kwargs)
return wrapper
# Decorator as a class method
@classmethod
def decorator2(cls, func):
@wraps(func)
def wrapper(*args, **kwargs):
print('Decorator 2')
return func(*args, **kwargs)
return wrapper
class Person:
# Create a property instance
first_name = property()
# Apply decorator methods
@first_name.getter
def first_name(self):
return self._first_name
@first_name.setter
def first_name(self, value):
if not isinstance(value, str):
raise TypeError('Expected a string')
self._first_name = value