ProgramingTip

@property 데코레이터는 어떻게 작동 작동합니까?

bestdevel 2020. 9. 28. 09:43
반응형

@property 데코레이터는 어떻게 작동 작동합니까?


내장 기능이 어떻게 property작동 하는지 이해하고 싶습니다 . 나를 혼란스럽게 property하는 것은 데코레이터로 사용할 인수를 사용하고 데코레이터로 사용할 수 있습니다.

이 예제는 문서 에서 장비 것입니다 .

class C(object):
    def __init__(self):
        self._x = None

    def getx(self):
        return self._x
    def setx(self, value):
        self._x = value
    def delx(self):
        del self._x
    x = property(getx, setx, delx, "I'm the 'x' property.")

property의 인수는 getx, setx, delx및 문서화 문자열.

아래 코드에서는 property데코레이터로 사용됩니다. 그것의 목적은 x함수이지만, 위의 코드에서는 인수에 개체 함수를위한 위치가 없습니다.

class C(object):
    def __init__(self):
        self._x = None

    @property
    def x(self):
        """I'm the 'x' property."""
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

    @x.deleter
    def x(self):
        del self._x

그리고 어떻게되어 x.setterx.deleter장식이 만들어 졌습니까? 혼란 스럽습니다.


property()함수는 특수 설명자 객체를 반환 합니다 .

>>> property()
<property object at 0x10ff07940>

추가 메서드 가있는 [해석]이 개체입니다 .

>>> property().getter
<built-in method getter of property object at 0x10ff07998>
>>> property().setter
<built-in method setter of property object at 0x10ff07940>
>>> property().deleter
<built-in method deleter of property object at 0x10ff07998>

이것들은 장식 자 역할 합니다. 새 속성 개체를 반환합니다.

>>> property().getter(None)
<property object at 0x10ff079f0>

이전 개체의 복사본이지만 함수 중 하나가 교체되었습니다.

@decorator구문은 단지 구문 적 설탕 이라는 것을 기억하십시오 . 구문 :

@property
def foo(self): return self._foo

정말 같은 의미

def foo(self): return self._foo
foo = property(foo)

그래서 foo함수는 대체 property(foo)됩니다. 위에서 보았던 것은 특별한 객체입니다. 그런 다음을 사용할 때 위에서 보여준 메서드를 @foo.setter()호출 property().setter하여 속성의 새 복사본을 반환하지만 이번에는 setter를 데코 레이팅 된 메서드로 바꿉니다.

다음 시퀀스는 기존 데코레이터 메소드를 사용하여 전체 속성을 만듭니다.

먼저 property게터만으로 몇 가지 함수와 object-를 만듭니다 .

>>> def getter(self): print 'Get!'
... 
>>> def setter(self, value): print 'Set to {!r}!'.format(value)
... 
>>> def deleter(self): print 'Delete!'
... 
>>> prop = property(getter)
>>> prop.fget is getter
True
>>> prop.fset is None
True
>>> prop.fdel is None
True

다음으로 .setter()setter를 추가하는 방법을 사용합니다 .

>>> prop = prop.setter(setter)
>>> prop.fget is getter
True
>>> prop.fset is setter
True
>>> prop.fdel is None
True

마지막으로 .deleter()메서드를 사용 하여 삭제 튼을 추가합니다 .

>>> prop = prop.deleter(deleter)
>>> prop.fget is getter
True
>>> prop.fset is setter
True
>>> prop.fdel is deleter
True

마지막 property객체 클래스는 역할을 설명 객체 가있다, 그래서 , 방법 설정 및 삭제, 점점 인스턴스에 후크 :.__get__().__set__().__delete__()

>>> class Foo(object): pass
... 
>>> prop.__get__(Foo(), Foo)
Get!
>>> prop.__set__(Foo(), 'bar')
Set to 'bar'!
>>> prop.__delete__(Foo())
Delete!

설명자 하우투에는 다음 유형 순수한 Python 샘플 구현 이 포함 되어 있습니다 property().

class Property(object):
    "Emulate PyProperty_Type() in Objects/descrobject.c"

    def __init__(self, fget=None, fset=None, fdel=None, doc=None):
        self.fget = fget
        self.fset = fset
        self.fdel = fdel
        if doc is None and fget is not None:
            doc = fget.__doc__
        self.__doc__ = doc

    def __get__(self, obj, objtype=None):
        if obj is None:
            return self
        if self.fget is None:
            raise AttributeError("unreadable attribute")
        return self.fget(obj)

    def __set__(self, obj, value):
        if self.fset is None:
            raise AttributeError("can't set attribute")
        self.fset(obj, value)

    def __delete__(self, obj):
        if self.fdel is None:
            raise AttributeError("can't delete attribute")
        self.fdel(obj)

    def getter(self, fget):
        return type(self)(fget, self.fset, self.fdel, self.__doc__)

    def setter(self, fset):
        return type(self)(self.fget, fset, self.fdel, self.__doc__)

    def deleter(self, fdel):
        return type(self)(self.fget, self.fset, fdel, self.__doc__)

문서에 따르면 읽기 전용 속성을 만드는 지름길 일뿐입니다. 그래서

@property
def x(self):
    return self._x

다음과 같다

def getx(self):
    return self._x
x = property(getx)

다음은 @property구현 방법에 대한 최소한의 예입니다 .

class Thing:
    def __init__(self, my_word):
        self._word = my_word 
    @property
    def word(self):
        return self._word

>>> print( Thing('ok').word )
'ok'

않으면 오는가 word속성 대신 메서드가 유지됩니다.

class Thing:
    def __init__(self, my_word):
        self._word = my_word
    def word(self):
        return self._word

>>> print( Thing('ok').word() )
'ok'

첫 번째 부분은 간단합니다.

@property
def x(self): ...

와 같다

def x(self): ...
x = property(x)
  • 이는 propertygetter만으로 를 생성하기위한 단순화 된 구문입니다 .

다음 단계는 setter 및 deleter를 사용하여이 속성을 확장하는 것입니다. 그리고 이는 적절한 방법으로 발생합니다.

@x.setter
def x(self, value): ...

이전 x값과 지정된 setter는 모든 것을 상속하는 새 속성을 반환합니다 .

x.deleter 같은 방식으로 작동합니다.


다음은 다음과 가변.

class C(object):
    def __init__(self):
        self._x = None

    @property
    def x(self):
        """I'm the 'x' property."""
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

    @x.deleter
    def x(self):
        del self._x

와 같다 :

class C(object):
    def __init__(self):
        self._x = None

    def _x_get(self):
        return self._x

    def _x_set(self, value):
        self._x = value

    def _x_del(self):
        del self._x

    x = property(_x_get, _x_set, _x_del, 
                    "I'm the 'x' property.")

와 같다 :

class C(object):
    def __init__(self):
        self._x = None

    def _x_get(self):
        return self._x

    def _x_set(self, value):
        self._x = value

    def _x_del(self):
        del self._x

    x = property(_x_get, doc="I'm the 'x' property.")
    x = x.setter(_x_set)
    x = x.deleter(_x_del)

와 같다 :

class C(object):
    def __init__(self):
        self._x = None

    def _x_get(self):
        return self._x
    x = property(_x_get, doc="I'm the 'x' property.")

    def _x_set(self, value):
        self._x = value
    x = x.setter(_x_set)

    def _x_del(self):
        del self._x
    x = x.deleter(_x_del)

다음과 달라집니다.

class C(object):
    def __init__(self):
        self._x = None

    @property
    def x(self):
        """I'm the 'x' property."""
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

    @x.deleter
    def x(self):
        del self._x

은 다음 여기@property 에서 가져온 코드를 리팩터링해야 우리 할 때 어떻게 도움이 될 수 있는지에, 대한 또 다른 예입니다 (아래에 요약 만 있습니다).

다음 Money과 같은 클래스를 고 가정해라 고 .

class Money:
    def __init__(self, dollars, cents):
        self.dollars = dollars
        self.cents = cents

사용자는 예를 들어 사용하는이 클래스에 따라 라이브러리를 만듭니다.

money = Money(27, 12)

print("I have {} dollar and {} cents.".format(money.dollars, money.cents))
# prints I have 27 dollar and 12 cents.

이제 Money클래스 를 변경 하고 dollarscents속성을 제거 하고 대신 총 센트 만 추적하기로 결정했다고 가정 해 보겠습니다 .

class Money:
    def __init__(self, dollars, cents):
        self.total_cents = dollars * 100 + cents

앞서 언급 한 사용자가 이전과 같이 자신의 라이브러리를 실행하려고

money = Money(27, 12)

print("I have {} dollar and {} cents.".format(money.dollars, money.cents))

오류가 발생합니다.

AttributeError : '돈'개체에 '달러'속성이 없습니다.

지금 당신의 원본에 의존하는 모든 사람 즉, Money클래스는 모든 코드 라인을 변경해야 dollars하고 cents매우 고통 스러울 수 있습니다 ... 그래서, 어떻게 피할 수 있는지? 사용하여 @property!

그 방법은 다음과 가능합니다.

class Money:
    def __init__(self, dollars, cents):
        self.total_cents = dollars * 100 + cents

    # Getter and setter for dollars...
    @property
    def dollars(self):
        return self.total_cents // 100

    @dollars.setter
    def dollars(self, new_dollars):
        self.total_cents = 100 * new_dollars + self.cents

    # And the getter and setter for cents.
    @property
    def cents(self):
        return self.total_cents % 100

    @cents.setter
    def cents(self, new_cents):
        self.total_cents = 100 * self.dollars + new_cents

지금 우리 도서관에서 전화하면

money = Money(27, 12)

print("I have {} dollar and {} cents.".format(money.dollars, money.cents))
# prints I have 27 dollar and 12 cents.

예상대로 작동하며 라이브러리에서 한 줄의 코드를 필요가 없습니다! 사실 우리가 의존하는 라이브러리는 사실조차 알 필요가 없습니다.

또한 setter잘 작동합니다.

money.dollars += 2
print("I have {} dollar and {} cents.".format(money.dollars, money.cents))
# prints I have 29 dollar and 12 cents.

money.cents += 10
print("I have {} dollar and {} cents.".format(money.dollars, money.cents))
# prints I have 29 dollar and 22 cents.

@property추상 클래스를 사용할 수 있습니다 . 여기서 최소한의 예를 들어 보겠습니다 .


여기에서 모든 게시물을 실제 사례가 필요합니다. 실제로 @property가있는 이유는 무엇입니까? 따라서 인증 시스템을 사용하는 Flask 앱을 ​​고려하십시오. 다음에서 모델 사용자를 선언합니다 models.py.

class User(UserMixin, db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(64), unique=True, index=True)
    username = db.Column(db.String(64), unique=True, index=True)
    password_hash = db.Column(db.String(128))

    ...

    @property
    def password(self):
        raise AttributeError('password is not a readable attribute')

    @password.setter
    def password(self, password):
        self.password_hash = generate_password_hash(password)

    def verify_password(self, password):
        return check_password_hash(self.password_hash, password)

이 코드에서는 사용자가 직접 액세스 할 때 어설 션 을 트리거하는 속성 password을 사용하여 "hidden"속성 을 사용 @property하는 AttributeError반면 @ property.setter를 사용하여 실제 인스턴스 변수를 설정했습니다 password_hash.

이제 다음을 사용 auth/views.py하여 사용자를 인스턴스화 할 수 있습니다.

...
@auth.route('/register', methods=['GET', 'POST'])
def register():
    form = RegisterForm()
    if form.validate_on_submit():
        user = User(email=form.email.data,
                    username=form.username.data,
                    password=form.password.data)
        db.session.add(user)
        db.session.commit()
...

password사용자가 양식을 채울 때 등록 양식에서 제공되는 알림 속성 입니다. 비밀번호 확인은 엔드 EqualTo('password', message='Passwords must match')에서 발생합니다 (궁금한 경우 다른 주제 관련 Flask 양식).

이 예제가 유용하기를 바랍니다.


이 지점은 저 위의 많은 사람들에 의해 해결됩니다. 이것이 @property 데코레이터로 시작하는 것이 중요하다고 생각합니다. 예 :-

class UtilityMixin():
    @property
    def get_config(self):
        return "This is property"

"get_config ()"함수 호출은 다음과 같이 작동합니다.

util = UtilityMixin()
print(util.get_config)

함수를 호출 할 때 "()"대괄호를 사용하지 않는 것을 알 수 있습니다. 이것은 @property 데코레이터를 검색 한 기본 것입니다. 따라서 함수를 변수처럼 사용할 수 있습니다.


Python 데코레이터부터 시작하겠습니다.

Python 데코레이터는 이미 정의 된 함수에 몇 가지 추가 기능을 추가하는 데 도움이되는 함수입니다.

수업에서는 모든 것이 수업입니다. Python의 함수는 일급 객체입니다. 즉, 변수로 참조하고, 목록에 추가하고, 다른 함수에 인수로 수 있습니다.

다음 코드 스 니펫을 고려하십시오.

def decorator_func(fun):
    def wrapper_func():
        print("Wrapper function started")
        fun()
        print("Given function decorated")
        # Wrapper function add something to the passed function and decorator 
        # returns the wrapper function
    return wrapper_func

def say_bye():
    print("bye!!")

say_bye = decorator_func(say_bye)
say_bye()

# Output:
#  Wrapper function started
#  bye
#  Given function decorated

여기서 데코레이터 함수가 say_hello 함수를 수정하고 코드 줄을 추가 말할 수 있습니다.

데코레이터를위한 예비 구문

def decorator_func(fun):
    def wrapper_func():
        print("Wrapper function started")
        fun()
        print("Given function decorated")
        # Wrapper function add something to the passed function and decorator 
        # returns the wrapper function
    return wrapper_func

@decorator_func
def say_bye():
    print("bye!!")

say_bye()

케이스 시나리오보다 모든 것을 결론 내렸지 만 그 전에 몇 가지 oops priniciples에 대해 이야기합시다.

게터와 세터는 데이터 캡슐화의 원칙을 보장하기 위해 많은 객체 지향 프로그래밍 언어에서 사용됩니다 (데이터에 대해 작동하는 메소드를 사용하여 데이터를 묶는 것).

다만 방법은 물론 데이터를 검색하는 게터이고 데이터를 변경하는 세터입니다.

이 원칙에 따라 클래스의 속성은 다른 코드에서 숨기고 보호하기 위해 비공개로 설정됩니다.

네, @property 는 기본적으로 getter와 setter를 사용 하는 방법입니다.

프로그래밍은 프로그래밍 프로그래머의 삶을 훨씬 더 단순하게 만드는 속성이라는 훌륭한 개념을 가지고 있습니다.

온도를 섭씨로 지정 수있는 클래스를 만들기로 결정하고 가정 해 보겠습니다.

class Celsius:
def __init__(self, temperature = 0):
    self.set_temperature(temperature)

def to_fahrenheit(self):
    return (self.get_temperature() * 1.8) + 32

def get_temperature(self):
    return self._temperature

def set_temperature(self, value):
    if value < -273:
        raise ValueError("Temperature below -273 is not possible")
    self._temperature = value

리팩토링 된 코드, 다음은 속성으로이를 달성 할 수있는 방법입니다.

Python에서 속성 ()은 속성 객체를 생성하고 반환하는 내장 함수입니다.

속성 객체에는 getter (), setter () 및 delete ()의 세 가지 메서드가 있습니다.

class Celsius:
def __init__(self, temperature = 0):
    self.temperature = temperature

def to_fahrenheit(self):
    return (self.temperature * 1.8) + 32

def get_temperature(self):
    print("Getting value")
    return self.temperature

def set_temperature(self, value):
    if value < -273:
        raise ValueError("Temperature below -273 is not possible")
    print("Setting value")
    self.temperature = value

temperature = property(get_temperature,set_temperature)

여기,

temperature = property(get_temperature,set_temperature)

다음과 같이 분해 될 수 있습니다.

# make empty property
temperature = property()
# assign fget
temperature = temperature.getter(get_temperature)
# assign fset
temperature = temperature.setter(set_temperature)

참고 사항 :

  • get_ temperature는 메서드 대신 속성으로 사용할 수 있습니다.

이제 쓰기를 통해 온도 값에 액세스 할 수 있습니다.

C = Celsius()
C.temperature
# instead of writing C.get_temperature()

우리는 더에 가서 이름이 아닌 정의 할 수 get_temperatureset_temperature 가 불필요하고, 클래스 네임 스페이스를 오염한다.

위의 문제를 처리 하는 비단뱀적인 방법@property 를 사용하는 것 입니다.

class Celsius:
    def __init__(self, temperature = 0):
        self.temperature = temperature

    def to_fahrenheit(self):
        return (self.temperature * 1.8) + 32

    @property
    def temperature(self):
        print("Getting value")
        return self.temperature

    @temperature.setter
    def temperature(self, value):
        if value < -273:
            raise ValueError("Temperature below -273 is not possible")
        print("Setting value")
        self.temperature = value

참고 사항-

  1. 값을 위해 사용되는 메소드는 "@property"로 장식됩니다.
  2. setter로 기능하는 방법은 "@ temperature.setter"로 장식되어 있고, 함수가 "x"로 불렸다면 "@ x.setter"로 장식해야합니다.
  3. 우리는 "def temperature (self)"및 "def temperature (self, x)"매개 변수의 개수가 같고 이름이 같은 "두 가지"방법을 작성했습니다.

보시다시피 코드는 확실히 덜 우아합니다.

이제 실제 실제 장면 하나에 대해 이야기 해 봅시다.

다음과 같이 클래스를 설계하고 가정 해 보겠습니다.

class OurClass:

    def __init__(self, a):
        self.x = a


y = OurClass(10)
print(y.x)

이제 우리 클래스가 클라이언트들 사이에서 인기를 프로그램에서 사용하기 시작하고 가정 해봅시다. 그들은 모든 종류의 할당을 받았습니다.

그리고 어느 운명의 날, 수있는 클라이언트가 우리에게 "x"는 0에서 1000 사이의 값을 제안했습니다. 이것은 정말 끔찍한 시나리오입니다!

속성으로 인해 제출. "x"의 속성 버전을 만듭니다.

class OurClass:

    def __init__(self,x):
        self.x = x

    @property
    def x(self):
        return self.__x

    @x.setter
    def x(self, x):
        if x < 0:
            self.__x = 0
        elif x > 1000:
            self.__x = 1000
        else:
            self.__x = x

이 대단하지 않습니다. 상상할 수있는 가장 간단한 구현으로 시작할 수 있고 나중에 인터페이스를 변경할 수있는 속성 버전으로 자유롭게 마이그레이션 할 수 있습니다! 따라서 속성은 getter 및 setter의 대체물이 아닙니다!

여기 에서이 구현을 확인할 수 있습니다.


property@property데코레이터 가있는 클래스 입니다.

찾을 수 있습니다.

print(property) #<class 'property'>

구문이 help(property)있음을 보여주기 위해 예제를 다시 작성했습니다.@property

class C:
    def __init__(self):
        self._x=None

    @property 
    def x(self):
        return self._x

    @x.setter 
    def x(self, value):
        self._x = value

    @x.deleter
    def x(self):
        del self._x

c = C()
c.x="a"
print(c.x)

기능적으로 property()구문 과 동일 합니다.

class C:
    def __init__(self):
        self._x=None

    def g(self):
        return self._x

    def s(self, v):
        self._x = v

    def d(self):
        del self._x

    prop = property(g,s,d)

c = C()
c.x="a"
print(c.x)

보시다시피 속성을 사용하는 방법에는 차이가 없습니다.

질문에 답하기 위해 @property데코레이터는 property클래스 를 통해 구현 됩니다.


그래서 문제는 property수업을 조금 설명하는 것 입니다. 이 줄 :

prop = property(g,s,d)

초기화되었습니다. 다음과 같이 다시 사용할 수 있습니다.

prop = property(fget=g,fset=s,fdel=d)

의 의미 fget, fset그리고 fdel:

 |    fget
 |      function to be used for getting an attribute value
 |    fset
 |      function to be used for setting an attribute value
 |    fdel
 |      function to be used for del'ing an attribute
 |    doc
 |      docstring

다음 이미지는 클래스에서 우리가 가지고있는 트리플렛을 보여줍니다 property.

여기에 이미지 설명 입력

__get__,, __set__무시할__delete__ 수 있습니다 . 이것은 서술에서 설명자 패턴의 구현입니다.

일반적으로 설명자는 "바인딩 동작"이있는 개체 속성으로, 설명자 프로토콜의 메서드에 의해 속성 액세스가 재정의되었습니다.

우리는 또한 속성을 사용할 수 setter있으며, getter그리고 deleter방법은 속성에 기능을 결합 할 수 있습니다. 다음 예를 확인하십시오. s2클래스 의 메서드 C는 속성을 두 배로 설정합니다 .

class C:
    def __init__(self):
        self._x=None

    def g(self):
        return self._x

    def s(self, x):
        self._x = x

    def d(self):
        del self._x

    def s2(self,x):
        self._x=x+x


    x=property(g)
    x=x.setter(s)
    x=x.deleter(d)      


c = C()
c.x="a"
print(c.x) # outputs "a"

C.x=property(C.g, C.s2)
C.x=C.x.deleter(C.d)
c2 = C()
c2.x="a"
print(c2.x) # outputs "aa"

속성은 두 가지 방법으로 선언 할 수 있습니다.

  • 속성에 대한 getter, setter 메서드를 만든 다음 속성 함수에 인수로 전달
  • @property의 장식을 사용.

python 속성에 대해 몇 가지 예제를 볼 수 있습니다 .


다음은 또 다른 예입니다.

##
## Python Properties Example
##
class GetterSetterExample( object ):
    ## Set the default value for x ( we reference it using self.x, set a value using self.x = value )
    __x = None


##
## On Class Initialization - do something... if we want..
##
def __init__( self ):
    ## Set a value to __x through the getter / setter... Since __x is defined above, this doesn't need to be set...
    self.x = 1234

    return None


##
## Define x as a property, ie a getter - All getters should have a default value arg, so I added it - it will not be passed in when setting a value, so you need to set the default here so it will be used..
##
@property
def x( self, _default = None ):
    ## I added an optional default value argument as all getters should have this - set it to the default value you want to return...
    _value = ( self.__x, _default )[ self.__x == None ]

    ## Debugging - so you can see the order the calls are made...
    print( '[ Test Class ] Get x = ' + str( _value ) )

    ## Return the value - we are a getter afterall...
    return _value


##
## Define the setter function for x...
##
@x.setter
def x( self, _value = None ):
    ## Debugging - so you can see the order the calls are made...
    print( '[ Test Class ] Set x = ' + str( _value ) )

    ## This is to show the setter function works.... If the value is above 0, set it to a negative value... otherwise keep it as is ( 0 is the only non-negative number, it can't be negative or positive anyway )
    if ( _value > 0 ):
        self.__x = -_value
    else:
        self.__x = _value


##
## Define the deleter function for x...
##
@x.deleter
def x( self ):
    ## Unload the assignment / data for x
    if ( self.__x != None ):
        del self.__x


##
## To String / Output Function for the class - this will show the property value for each property we add...
##
def __str__( self ):
    ## Output the x property data...
    print( '[ x ] ' + str( self.x ) )


    ## Return a new line - technically we should return a string so it can be printed where we want it, instead of printed early if _data = str( C( ) ) is used....
    return '\n'

##
##
##
_test = GetterSetterExample( )
print( _test )

## For some reason the deleter isn't being called...
del _test.x

기본적으로 x를 대신 사용한다는 점을 제외하면 C (객체)와 동일 합니다. 또한 __init에서 초기화하지 않습니다 . .-... 음 .. 그렇습니다.하지만 __x가 일부로 있기 때문에 제거 할 수 있습니다. 수업의 ....

출력은 다음과 가변합니다.

[ Test Class ] Set x = 1234
[ Test Class ] Get x = -1234
[ x ] -1234

init 에서 self.x = 1234를 주석 처리 하면 출력은 다음과 가변됩니다.

[ Test Class ] Get x = None
[ x ] None

그리고 getter 함수에서 _default = None을 _default = 0으로 설정하면 (모든 게터는 정의를 가져야하지만 내가 본 본의 속성 값에 의해 전달되지 않은 것에서 정의 할 수 있습니다. 있기 때문에 실제로 나쁘지 발음합니다.) 예 : def x (self, _default = 0) :

[ Test Class ] Get x = 0
[ x ] 0

참고 : getter 논리는 값을 조작하여 값을 조작하도록하기위한 것입니다. print 문 마찬가지입니다.

참고 : 저는 Lua에 익숙하고 하나의 함수를 호출 할 때 10 이상의 도우미를 동적으로 만들 수 있지만 사용하지 않고 Python에 대해 속성을 만들거나 어느 정도 작동하지만 함수가 사용 중이지만 생성합니다. 되기 전에 호출되는 문제가 여전히 있습니다. 나는 Lua 메타 테이블의 유연성과 실제 세터 / 게를 사용할 수 있습니다 사실을 선호합니다. 내장으로 변수에 직접 접근하는 대신 ... 저는 그리고 얼마나 빨리 빌드 할 수 있는지를 좋아합니다. 예를 들어 gui 프로그램입니다. 내가 디자인하고있는 것은 많은 추가 라이브러리 없이는 불가능할 수도 있습니다. AutoHotkey에서 코드를 작성하면 필요한 dll 호출에 직접 액세스 할 수 있습니다. Java, C #, C ++에서 동일한 작업을 수행 할 수 있습니다.

참고 :이 포럼의 코드 출력이 깨졌습니다. 코드의 첫 번째 부분에 공백을 추가해야합니다. 복사 / 추가 넣기를 모든 공백을 탭으로 변환 할 수 있습니다. .... 저는 Python 용 탭을 사용합니다. 파일 크기가 10,000 행인 파일 크기는 512KB에서 1MB (공백 포함), 100-200KB (탭 포함)는 파일 크기에 대한 엄청난 차이와 처리 시간에 해당합니다.

탭은 사용자 가능합니다. 따라서 2 개, 4 개, 8 개 또는 무엇이든 할 수있는 모든 것을 선호하는 경우에 부족한 개발자에게 신중함을 의미합니다.

참고 : 포럼 소프트웨어의 버그로 인해 클래스에 정의 된 모든 함수가 들여 쓰기되지 않습니다. 복사 / 넣기를 할 때 들여 쓰기를해야합니다.


한 가지 언급 : 파이썬 2.x에서의 @property경우 object다음 에서 상속하지 않았을 때 광고 된대로 작동하지 않았습니다 .

class A():
    pass

그러나 다음과 같은 경우에 일했습니다.

class A(object):
    pass

Python 3의 경우 항상 작동했습니다.

참고 URL : https://stackoverflow.com/questions/17330160/how-does-the-property-decorator-work

반응형