2014-10-23 2 views
0

는 클래스의 속성을 결정하는 방법은 __get____set__ 여부와 (A Property이 있습니까? Determine if given class attribute is a property or not, Python object에있어서, 단지 내 경우에는 작동되지 property 장식, 작동 보인다처럼.클래스 속성이 Property인지 확인 하시겠습니까?

class Property(object): 
    _value = None 
    def __get__(self, instance, owner): 
     return self._value 
    def __set__(self, instance, value): 
     self._value = value * 2 


class A(object): 
    b = Property() 

>>> a = A() 
>>> type(A.p) 
<type 'NoneType'> 
>>> type(a.p) 
<type 'NoneType'> 
+1

올바른 용어는 '설명자'입니다. [descriptor HOWTO] (https://docs.python.org/2/howto/descriptor.html) –

답변

1
( __get__ 해당 시나리오에 대해 호출 될 때 instance 속성이 None로 설정) 그것은 또한 클래스에 대해 호출 때문에

귀하의 설명은 None를 반환합니다.

당신은 클래스 __dict__ 속성에 도달,는 설명 프로토콜을 호출하지 않고 를 검색해야하는 가장 직접적인 경로 :

A.__dict__['p'] 

이 기술자를 호출하는 방법과시기에 대한 자세한 내용은 Python Descriptor HOWTO를 참조하십시오.

달리, property 객체 마찬가지로 않고 instanceNone로 설정되어있는 경우 (따라서 클래스에 액세스 할 때) self를 반환 :

class Property(object): 
    _value = None 
    def __get__(self, instance, owner): 
     if instance is None: 
      return self 
     return self._value 
    def __set__(self, instance, value): 
     self._value = value * 2 

를 참조 How does the @property decorator work?

데모 :

>>> class Property(object): 
...  def __get__(self, instance, owner): 
...   return self._value 
...  def __set__(self, instance, value): 
...   self._value = value * 2 
... 
>>> class A(object): 
...  b = Property() 
... 
>>> A.__dict__['b'] 
<__main__.Property object at 0x103097910> 
>>> type(A.__dict__['b']) 
<class '__main__.Property'> 
>>> class Property(object): 
...  _value = None 
...  def __get__(self, instance, owner): 
...   if instance is None: 
...    return self 
...   return self._value 
...  def __set__(self, instance, value): 
...   self._value = value * 2 
... 
>>> class A(object): 
...  b = Property() 
... 
>>> A.b 
<__main__.Property object at 0x10413d810> 
+0

위대한 설명과 참고 자료가 유용하다 !! – lucemia