>  기사  >  백엔드 개발  >  Python 속성 및 설명자 사용

Python 속성 및 설명자 사용

高洛峰
高洛峰원래의
2017-02-25 10:32:131016검색

@property 데코레이터 정보

Python에서는 @property 데코레이터를 사용하여 함수 호출을 속성에 대한 액세스로 위장합니다.

그럼 왜 이러는 걸까요? @property를 사용하면 클래스의 속성에 액세스하기 위한 간단한 인터페이스를 유지하면서 사용자 정의 코드를 변수 액세스/설정과 연결할 수 있기 때문입니다.

예를 들어 영화를 표현해야 하는 클래스가 있는 경우:

class Movie(object):
 def __init__(self, title, description, score, ticket):
 self.title = title
 self.description = description
 self.score = scroe
 self.ticket = ticket

이 클래스를 다른 곳에서 사용하기 시작합니다. 하지만 실수로 영화에 부정적인 점수를 주었다면 어떻게 될까요? 여러분은 이것이 잘못된 동작이라고 생각하고 Movie 클래스가 이 오류를 방지할 수 있기를 바랍니다. 첫 번째 생각은 Movie 클래스를 다음과 같이 수정하는 것입니다.

class Movie(object):
 def __init__(self, title, description, score, ticket):
 self.title = title
 self.description = description
     self.ticket = ticket
 if score < 0:
  raise ValueError("Negative value not allowed:{}".format(score))
 self.score = scroe

하지만 그러면 작동하지 않습니다. 코드의 다른 부분은 Movie.score를 통해 직접 할당되기 때문입니다. 새로 수정된 이 클래스는 __init__ 메서드에서 잘못된 데이터만 캡처하지만 기존 클래스 인스턴스에 대해서는 아무 작업도 수행할 수 없습니다. 누군가 m.scrore= -100을 실행하려고 하면 이를 중지할 수 있는 방법이 없습니다. 무엇을 해야 할까요?

Python의 속성이 이 문제를 해결합니다.

할 수 있습니다

class Movie(object):
 def __init__(self, title, description, score):
 self.title = title
 self.description = description
 self.score = score
     self.ticket = ticket
 
 @property
 def score(self):
 return self.__score
 
 
 @score.setter
 def score(self, score):
 if score < 0:
  raise ValueError("Negative value not allowed:{}".format(score))
 self.__score = score
 
 @score.deleter
 def score(self):
 raise AttributeError("Can not delete score")

이렇게 하면 어디에서나 점수를 수정하면 0보다 작은지 여부를 감지할 수 있습니다.

속성의 단점

속성의 가장 큰 단점은 재사용이 불가능하다는 점이다. 예를 들어 티켓 필드에도 음수가 아닌 검사를 추가한다고 가정해 보겠습니다.

수정된 새 클래스는 다음과 같습니다.

class Movie(object):
 def __init__(self, title, description, score, ticket):
 self.title = title
 self.description = description
 self.score = score
 self.ticket = ticket
 
 @property
 def score(self):
 return self.__score
 
 
 @score.setter
 def score(self, score):
 if score < 0:
  raise ValueError("Negative value not allowed:{}".format(score))
 self.__score = score
 
 @score.deleter
 def score(self):
 raise AttributeError("Can not delete score")
 
 
 @property
 def ticket(self):
 return self.__ticket
 
 @ticket.setter
 def ticket(self, ticket):
 if ticket < 0:
  raise ValueError("Negative value not allowed:{}".format(ticket))
 self.__ticket = ticket
 
 
 @ticket.deleter
 def ticket(self):
 raise AttributeError("Can not delete ticket")

코드가 많이 늘어난 것을 볼 수 있지만, 반복되는 로직도 있습니다. . 약간의. 속성은 클래스의 인터페이스를 외부에서 깨끗하고 아름답게 보이게 할 수 있지만 내부적으로는 깨끗하고 아름다울 수 없습니다.

설명어가 나타납니다

설명어란 무엇인가요?

일반적으로 설명자는 바인딩 동작이 있는 개체 속성이며 해당 속성에 대한 액세스는 설명자 프로토콜 메서드에 의해 재정의됩니다. 이러한 메서드는 __get__(), __set__() 및 __delete__()입니다. 객체에 이 세 가지 메서드 중 적어도 하나가 포함되어 있으면 이를 설명자라고 합니다.

설명자는 무엇을 합니까?

속성 액세스의 기본 동작은 객체 사전에서 속성을 가져오거나 설정하거나 삭제하는 것입니다. 예를 들어 a.x에는 a.__dict__['x']로 시작하는 조회 체인이 있고(a ) .__dict__['x'], 그리고 메타클래스를 제외하고 type(a)의 기본 클래스를 계속 진행합니다. 조회된 값이 설명자 메서드 중 하나를 정의하는 객체인 경우 Python은 기본 동작을 재정의하고 설명자를 호출할 수 있습니다. 우선 순위 체인에서 이것이 발생하는 위치는 정의된 설명자 메서드에 따라 다릅니다. —–공식 문서에서 발췌

간단히 말해서 설명자는 속성을 가져오고 설정하고 삭제하는 기본 방법을 변경합니다.

먼저 위의 반복 속성 논리 문제를 해결하기 위해 설명자를 사용하는 방법을 살펴보겠습니다.

class Integer(object):
 def __init__(self, name):
 self.name = name
 
 def __get__(self, instance, owner):
 return instance.__dict__[self.name]
 
 def __set__(self, instance, value):
 if value < 0:
  raise ValueError("Negative value not allowed")
 instance.__dict__[self.name] = value
 
class Movie(object):
 score = Integer(&#39;score&#39;)
 ticket = Integer(&#39;ticket&#39;)

설명자는 우선순위가 높고 Movie().score에 액세스하거나 설정할 때 기본 get 및 set 동작을 이러한 방식으로 변경하기 때문입니다. 항상 설명자 Integer에 의해 제한됩니다.

그러나 항상 다음과 같은 방식으로 인스턴스를 생성할 수는 없습니다.

a = Movie()
a.score = 1
a.ticket = 2
a.title = ‘test&#39;
a.descript = ‘…&#39;

너무 무뚝뚝해서 아직 생성자가 부족합니다.

class Integer(object):
 def __init__(self, name):
 self.name = name
 
 def __get__(self, instance, owner):
 if instance is None:
  return self
 return instance.__dict__[self.name]
 
 def __set__(self, instance, value):
 if value < 0:
  raise ValueError(&#39;Negative value not allowed&#39;)
 instance.__dict__[self.name] = value
 
 
class Movie(object):
 score = Integer(&#39;score&#39;)
 ticket = Integer(&#39;ticket&#39;)
 
 def __init__(self, title, description, score, ticket):
 self.title = title
 self.description = description
 self.score = score
 self.ticket = ticket

이렇게 하면 점수와 티켓을 가져오고 설정하고 삭제할 때 Integer의 __get__, __set__이 입력되므로 반복되는 논리가 줄어듭니다.

이제 문제가 해결되었으므로 이 설명자가 실제로 어떻게 작동하는지 궁금하실 것입니다. 구체적으로 __init__ 함수에서 액세스되는 것은 자체 self.score 및 self.ticket이며 클래스 속성 점수 및 티켓과 어떤 관련이 있습니까?

설명자 작동 방식

공식 설명 보기

객체가 __get__()과 __set__()을 모두 정의하는 경우 __get__만 정의하는 데이터 설명자로 간주됩니다. ()는 비데이터 설명자라고 합니다(일반적으로 메서드에 사용되지만 다른 용도도 가능합니다).

데이터 설명자와 비데이터 설명자는 인스턴스 사전의 항목과 관련하여 재정의가 계산되는 방식이 다릅니다. 인스턴스의 사전에 데이터 설명자와 이름이 같은 항목이 있으면 데이터 설명자가 우선합니다. 인스턴스의 사전에 데이터 설명자가 아닌 항목과 이름이 같은 항목이 있으면 사전 항목이 우선합니다.

기억해야 할 중요한 사항은 다음과 같습니다.

설명자는 __getattribute__() 메서드에 의해 호출됩니다
__getattribute__()를 재정의하면 자동 설명자 호출이 방지됩니다
object.__getattribute__()와 type.__getattribute__()는 서로 달라집니다 __get__()에 대한 호출.
데이터 설명자는 항상 인스턴스 사전을 재정의합니다.
비데이터 설명자는 인스턴스 사전에 의해 재정의될 수 있습니다.

클래스가 __getattribute__()를 호출하면 아마도

def __getattribute__(self, key):
 "Emulate type_getattro() in Objects/typeobject.c"
 v = object.__getattribute__(self, key)
 if hasattr(v, &#39;__get__&#39;):
 return v.__get__(None, self)
 return v

다음은 해외 블로그에서 발췌한 내용입니다.

클래스 "C"와 인스턴스 "c"(여기서 "c = C(...)")가 주어지면 "c.name"을 호출한다는 것은 인스턴스 "c"에서 속성 "name"을 찾는 것을 의미합니다. :

Get the Class from Instance
Call the Class's special method getattribute__. All objects have a default __getattribute
Inside getattribute

Get the Class's mro as ClassParents
For each ClassParent in ClassParents
If the Attribute is in the ClassParent's dict
If is a data descriptor
Return the result from calling the data descriptor's special method __get__()
Break the for each (do not continue searching the same Attribute any further)
If the Attribute is in Instance's dict
Return the value as it is (even if the value is a data descriptor)
For each ClassParent in ClassParents
If the Attribute is in the ClassParent's dict
If is a non-data descriptor
Return the result from calling the non-data descriptor's special method __get__()
If it is NOT a descriptor
Return the value
If Class has the special method getattr
Return the result from calling the Class's special method__getattr__.

我对上面的理解是,访问一个实例的属性的时候是先遍历它和它的父类,寻找它们的__dict__里是否有同名的data descriptor如果有,就用这个data descriptor代理该属性,如果没有再寻找该实例自身的__dict__ ,如果有就返回。任然没有再查找它和它父类里的non-data descriptor,最后查找是否有__getattr__

描述符的应用场景

python的property、classmethod修饰器本身也是一个描述符,甚至普通的函数也是描述符(non-data discriptor)

django model和SQLAlchemy里也有描述符的应用

class User(db.Model):
 id = db.Column(db.Integer, primary_key=True)
 username = db.Column(db.String(80), unique=True)
 email = db.Column(db.String(120), unique=True)
 
 def __init__(self, username, email):
 self.username = username
 self.email = email
 
 def __repr__(self):
 return &#39;<User %r>' % self.username

总结

只有当确实需要在访问属性的时候完成一些额外的处理任务时,才应该使用property。不然代码反而会变得更加啰嗦,而且这样会让程序变慢很多。以上就是本文的全部内容,由于个人能力有限,文中如有笔误、逻辑错误甚至概念性错误,还请提出并指正。

更多Python属性和描述符的使用相关文章请关注PHP中文网!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.