2016-11-25 5 views
-1

様々なセッターとゲッターを作りたい。コードをコピー&ペーストしないで、私はそれを解決する何かを考えました。デコレータはできますか?デコレータはセッターとゲッターをPythonでラップできますか?

@property 
def !!variable_name!!(self): 
    return self.__!!variable_name!! 

@!!variable_name!!.setter 
def !!variable_name!!(self, input): 
    self.__!!variable_name!! = input 

Cのマクロのように可能ですか?

答えて

0

簡単な答え:はい、それは記述子プロトコルを使用して可能です。たとえば、あなたは、先頭にアンダースコアで変数を保存し、大手せずにアクセスしたい、そのような記述が働くだろうアンダースコア:

from six import string_types 

class DescriptorSingleLeadingUnderscore(object): 
    def __init__(self, attr, doc=""): 
     if not isinstance(attr, string_types): 
      # Not a string so take the documentation (if avaiable) and name 
      # from the method. 
      if attr.__doc__: 
       doc = attr.__doc__ 
      attr = attr.__name__ 

     self.__doc__ = doc  # Set the documentation of the instance. 
     self.attr = '_' + attr # Add leading underscore to the attribute name 

    def __get__(self, instance, owner=None): 
     if instance is None: 
      return self 
     return getattr(instance, self.attr, None) 

    def __set__(self, instance, value): 
     setattr(instance, self.attr, value) 

    def __delete__(self, instance): 
     delattr(instance, self.attr) 

class X(object): 
    someproperty = DescriptorSingleLeadingUnderscore('someproperty') 
    someproperty1 = DescriptorSingleLeadingUnderscore('someproperty1') 
    someproperty2 = DescriptorSingleLeadingUnderscore('someproperty2') 
    someproperty3 = DescriptorSingleLeadingUnderscore('someproperty3') 

    @DescriptorSingleLeadingUnderscore 
    def it_also_works_as_decorator(self): 
     pass # this code is never executed! 

とテストケース:

>>> x = X() 

>>> x.someproperty = 100 
>>> x.someproperty 
100 
>>> x._someproperty 
100 

>>> x.it_also_works_as_decorator = 100 
>>> x.it_also_works_as_decorator 
100 
>>> x._it_also_works_as_decorator 
100 
0

あなたがしたいと思う理由は不明ですこの作成し、その値引数を-が、無視答えはでセッターを持つプロパティを「はい」ような何かを、カスタムpropertyオブジェクトを返す関数を作成することによってそれを行うことができます。

ただし、@構文を使用して適用することはできません。代わりに、あなたは、図示のように、それを利用する必要があります。

def attribute_property(name, input_value): 
    STORAGE_NAME = '_' + name 

    @property 
    def prop(self): 
     return getattr(self, STORAGE_NAME) 

    @prop.setter 
    def prop(self, ignored): 
     setattr(self, STORAGE_NAME, input_value) 

    return prop 

# EXAMPLE USAGE 
class Person(object): 
    name = attribute_property('name', 'Monty') 

    def __init__(self, name, age): 
     self.name = name # ignores value of passed "name" argument! 
     self.age = age 

user = Person('Rodrigo', 42) 
print('user.name: {!r}'.format(user.name)) 
print('user.age: {!r}'.format(user.age)) 

出力:

user.name: 'Monty' 
user.age: 42 
+1

マイナータイプミス: 'self.name - NAME'は右、' self.name = NAME'すべきですか? – MSeifert

関連する問題