Python에서는 @property decorator가 어떻게 동작합니까?
빌트인 기능이 어떻게 기능하는지 알고 싶습니다.property
스럽게 하는 것은 가가 works works works works works works works works works worksproperty
데코레이터로도 사용할 수 있지만 내장 기능으로 사용할 경우 인수만 사용할 수 있으며 데코레이터로 사용할 경우 인수만 사용할 수 있습니다.
다음 예시는 매뉴얼에 기재되어 있습니다.
class C:
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:
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.setter
★★★★★★★★★★★★★★★★★」x.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
위에서 보여드린 메서드에서는 새로운 속성 복사가 반환됩니다만, 이번에는 세터 기능이 장식된 메서드로 대체되었습니다.
다음 시퀀스는 이러한 장식기 메서드를 사용하여 풀온 속성을 만듭니다.
몇 와 을 .property
: getter만 있는 오브젝트:
>>> 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()
다음 중 하나:
>>> 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
오브젝트는 디스크립터 오브젝트로서 기능하기 때문에, 및 인스턴스 어트리뷰트의 취득, 설정, 삭제에 후크 하는 메서드가 있습니다.
>>> class Foo: pass
...
>>> prop.__get__(Foo(), Foo)
Get!
>>> prop.__set__(Foo(), 'bar')
Set to 'bar'!
>>> prop.__delete__(Foo())
Delete!
Descriptor Howto에는 Python의 순수 샘플 구현이 포함되어 있습니다.property()
삭제:
class Property: "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)
- 「」, 「」, 「」를 구문입니다.
property
겟터만 있으면 돼
다음 단계는 설정자와 삭제자를 사용하여 이 속성을 확장하는 것입니다.이것은 적절한 방법으로 이루어집니다.
@x.setter
def x(self, value): ...
하는 새 합니다.x
주어진 세터를 더합니다.
x.deleter
같은 방법으로 동작합니다.
에 또 .@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
하여 "disclass"를 합니다.dollars
★★★★★★★★★★★★★★★★★」cents
대신 총 센트의 양만을 추적하기로 결정합니다.
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' 특성이 없습니다.
, 하고 있는 에 와서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
추상적인 수업에서도 최소한의 예를 들겠습니다.
다음 항목:
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
Python 데코레이터부터 시작합시다.
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_bye 기능을 변경하여 코드 행을 추가했다고 할 수 있습니다.
장식기의 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
@decorator_func
def say_bye():
print("bye!!")
say_bye()
사건 시나리오로 모든 것을 살펴봅시다.그 전에 OOP의 원리에 대해 설명하겠습니다.
getters와 setters는 많은 객체 지향 프로그래밍 언어에서 데이터 캡슐화의 원리를 보장하기 위해 사용됩니다(이러한 데이터에서 동작하는 메서드로 데이터를 번들링하는 것으로 간주됩니다).
물론 이러한 메서드는 데이터를 취득하기 위한 getter와 데이터를 변경하기 위한 setter입니다.
이 원리에 따르면 클래스의 속성은 다른 코드로부터 숨기고 보호하기 위해 비공개로 설정됩니다.
네, @property는 기본적으로 getter와 setter를 사용하는 피조어적인 방법입니다.
Python은 객체 지향 프로그래머의 삶을 훨씬 단순하게 만드는 속성이라는 훌륭한 개념을 가지고 있다.
여러분이 온도를 섭씨로 저장할 수 있는 클래스를 만들기로 결정했다고 가정해 보겠습니다.
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
리팩터링된 코드, 'property'로 이를 달성할 수 있었던 방법은 다음과 같습니다.
Python에서 property()는 속성 개체를 만들고 반환하는 내장 함수입니다.
속성 오브젝트에는 getter(), setter() 및 delete()의 3가지 메서드가 있습니다.
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_temperature 및 set_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
주의사항 -
- 값을 얻기 위해 사용되는 메서드는 "@property"로 장식됩니다.
- 세터로서 기능해야 할 메서드는 "@temperature"로 장식되어 있습니다.setter"라고 하면 함수를 "x"라고 불렀다면 "@x.setter"로 장식해야 합니다.
- 우리는 "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
이것은 매우 훌륭합니다.상상 가능한 가장 간단한 구현부터 시작할 수 있으며 나중에 인터페이스를 변경하지 않고도 속성 버전으로 자유롭게 이행할 수 있습니다.자산은 단순히 게터나 세터를 대체하는 것이 아닙니다!
이 실장은 이쪽에서 확인할 수 있습니다.
나는 여기 있는 모든 게시물을 읽고 우리에게 실제 삶의 예가 필요할지도 모른다는 것을 깨달았다.@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ propertyproperty따라서 인증 시스템을 사용하는 플라스크 앱을 고려해 보십시오.합니다.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
를 사용하여@property
에, 「」가 트리거 됩니다.AttributeError
실제 변수 세터를 하기 위한 @setter의 어설션.: " assertion " 。 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')
(궁금하실지 모르겠지만 플라스크 폼과 관련된 다른 주제입니다).
이 예가 유용했으면 좋겠다.
이 지점은 많은 사람들에 의해 제거되었지만 내가 찾고 있던 직접적인 지점은 여기 있다.@property decorator부터 시작하는 것이 중요하다고 생각합니다.예:-
class UtilityMixin():
@property
def get_config(self):
return "This is property"
함수 "get_config()" 호출은 다음과 같이 동작합니다.
util = UtilityMixin()
print(util.get_config)
함수를 호출할 때 괄호를 사용하지 않은 것을 알 수 있습니다.@property decorator를 찾고 있던 기본 사항입니다.변수처럼 함수를 사용할 수 있습니다.
가장 좋은 설명은 여기에서 찾을 수 있습니다: Python @Property Descriptions – How to Use and When? (전체 예) by Selva Prabhakaran | 2018년 11월 5일 게시
그것은 내가 왜 방법만이 아닌지를 이해하는데 도움을 주었다.
https://www.machinelearningplus.com/python/python-property/
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)
으로는 is is is to to to to to to 와 동일합니다.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
는 데코레 decor decor를 통해 구현됩니다.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__
덮어쓸 필요가 있습니다.이것은 Python에서 기술자 패턴을 구현한 것입니다.
일반적으로 기술자는 "바인딩 동작"을 가진 객체 속성이며, 그 속성 액세스는 기술자 프로토콜의 메서드에 의해 재정의됩니다.
는 또한 할 수 있습니다.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"
데코레이터는 함수를 인수로 사용하여 닫힘을 반환하는 함수입니다.폐쇄는 내부 함수와 자유 변수의 집합입니다.내부 함수는 자유 변수 위에 닫히고 있으며, 이것이 바로 '닫힘'이라고 불리는 이유입니다.자유 변수는 내부 함수를 벗어나 도코레이터를 통해 내부로 전달되는 변수입니다.
이름 그대로 데코레이터가 받은 기능을 데코레이션하고 있습니다.
function decorator(undecorated_func):
print("calling decorator func")
inner():
print("I am inside inner")
return undecorated_func
return inner
이치노"()에 전달하고()는 "I하여 "undecorated_func"를 했습니다.undecorated_func
「 」를 했을 때decorator(undecorated_func)
, , , , , , , 을 .inner
여기 키가 있습니다. 데코레이터에서는 전달한 함수의 이름으로 내부 함수를 명명하고 있습니다.
undecorated_function= decorator(undecorated_func)
현재 내부 함수는 "componated_func"라고 불립니다.inner는 undecorated_func로 명명되어 있기 때문에 undecorated_func를 데코레이터에게 전달하고 undecorated_func를 반환하고 undecorated_func를 인쇄하여 undecorated_func를 장식하였습니다.
이제 속성 데코레이터를 사용하여 클래스를 정의합니다.
class Person:
def __init__(self,name):
self._name=name
@property
def name(self):
return self._name
@name.setter
def name(self.value):
self._name=value
name()을 @display로 장식하면 다음과 같이 됩니다.
name=property(name) # Person.__dict__ you ll see name
property()의 첫 번째 인수는 getter입니다.두 번째 장식은 다음과 같습니다.
name=name.setter(name)
앞에서 말씀드린 바와 같이, 데코레이터가 내부 함수를 반환하고, 전달한 기능의 이름으로 내부 함수를 명명합니다.
여기 주의해야 할 중요한 것이 있습니다."name"은 불변입니다.첫 번째 장식에서는 다음과 같은 것이 있습니다.
name=property(name)
두 번째에 우리는 이것을 얻었다.
name=name.setter(name)
이름 obj는 수정하지 않습니다.두 번째 장식에서는 python은 이것이 속성 객체이며 이미 getter가 있음을 인식합니다.따라서 python은 새로운 "name" 개체를 만들고 첫 번째 obj에서 "fget"을 추가한 다음 "fset"을 설정합니다.
속성은 두 가지 방법으로 선언할 수 있습니다.
- 속성에 대한 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
기본적으로는 C(object)의 예시와 동일하지만 x를 대신 사용하고 있습니다. 저도 __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으로 설정했을 경우(모든 getter에는 기본값이 있어야 하지만 여기서 정의할 수 있도록 속성값으로는 전달되지 않으며 기본값을 한 번 정의하고 모든 곳에서 사용할 수 있으므로 실제로 나쁘지 않습니다). 즉, def x(self, _default = 0):
[ Test Class ] Get x = 0
[ x ] 0
주의: getter 로직은 값이 조작되도록 하기 위해서만 존재합니다.인쇄문에서도 마찬가지입니다.
주의: Lua에 익숙하여 단일 함수를 호출할 때 10개 이상의 도움말을 동적으로 생성할 수 있으며, 속성을 사용하지 않고 Python을 위해 비슷한 것을 만들어 어느 정도 동작합니다만, 함수를 사용하기 전에 호출하는 것은 아직 문제가 있습니다.그런 식으로 코드화 되어 있지 않기 때문에...저는 Lua 메타테이블의 유연성과 변수에 직접 액세스하는 대신 실제 세터/게터를 사용할 수 있다는 사실을 선호합니다.Python으로 빠르게 빌드할 수 있는 것이 마음에 듭니다.예를 들어 gui 프로그램입니다.내가 설계하고 있는 것은 많은 추가 라이브러리 없이는 불가능할 수 있지만 - AutoHotkey로 코드화하면 필요한 dll 호출에 직접 액세스할 수 있고 Java, C#, C++ 등에서도 동일한 작업을 수행할 수 있습니다 - 아마도 나는 아직 적절한 것을 찾지 못했지만 Python에서 전환할 수 있습니다.
주의: 이 포럼의 코드 출력은 파손되어 있습니다.코드의 첫 부분에 공백이 추가되어 동작합니다.복사/붙여넣기 시 모든 공간을 탭으로 변환할 수 있습니다.Python용 탭을 사용하는 이유는 10,000줄의 파일 사이즈는 공백이 있는 512KB에서 1MB, 탭이 있는 100에서 200KB까지 가능하기 때문입니다.이것은 파일 사이즈의 큰 차이와 처리 시간의 단축에 해당합니다.
탭은 유저 마다 조정할 수도 있습니다.따라서, 2 스페이스의 너비, 4 스페이스, 8 스페이스등의 조작이 가능한 경우는, 시력이 부족한 개발자에게 있어서 배려가 필요합니다.
주의: 포럼 소프트웨어의 버그로 인해 클래스에 정의되어 있는 모든 함수가 올바르게 들여쓰기되지 않았습니다.복사/붙여넣을 경우 들여쓰기해야 합니다.
언급URL : https://stackoverflow.com/questions/17330160/how-does-the-property-decorator-work-in-python
'itsource' 카테고리의 다른 글
PHP에서 사용할 압축 방법을 선택하십시오. (0) | 2023.01.19 |
---|---|
속성 값을 기준으로 개체 배열 정렬 (0) | 2023.01.19 |
MySQL FK의 적절한 명명 규칙은 무엇입니까? (0) | 2023.01.19 |
mysql 데이터베이스에 슈퍼 권한을 추가하는 방법 (0) | 2023.01.19 |
하위 행을 추가하거나 업데이트할 수 없음: 외부 키 제약 조건이 실패합니다. (0) | 2023.01.19 |