python property의 사용 기교 공유
property 속성
실례 속성을 사용하는 것과 같은 특수한 속성으로 어떤 방법에 대응할 수 있다
클래스의 봉인 특성을 보호해야 할 뿐만 아니라 개발자가 대상을 사용할 수 있도록 해야 한다.속성의 방식 조작 방법, @property 장식기, 방법 이름을 통해 접근할 수 있으며, 방법 이름 뒤에 () 괄호를 추가할 필요가 없습니다.
원 의 면적 을 구하는 예 를 보다
class Circle(object):
PI = 3.14
def __init__(self, r):
# r
self.r = r
self.__area = self.PI * self.r * self.r
@property
def area(self):
return self.__area
def get_area(self):
return self.__area
In [2]: c = Circle(10)
In [3]: c.area
Out[3]: 314.0
In [4]: c.get_area()
Out[4]: 314.0
property 속성의 정의와 호출은 몇 가지를 주의해야 합니다.
property 장식 방법: c.area
구체적인 실례
어떤 상점에 컴퓨터 호스트의 목록 페이지를 표시할 때 매번 요청할 때마다 데이터베이스에 있는 모든 내용을 페이지에 표시할 수 없고 페이지의 기능을 통해 부분적으로 표시하기 때문에 데이터베이스에 데이터를 요청할 때 표시할 지정은 m조에서 n조까지의 모든 데이터를 가져오는 기능을 포함한다.
class Pager(object):
def __init__(self, current_page):
# ( 、 ...)
self.current_page = current_page
# 10
self.per_items = 10
@property
def start(self):
val = (self.current_page - 1) * self.per_items
return val
@property
def end(self):
val = self.current_page * self.per_items
return val
# ipython
In [2]: p = Pager(1)
In [3]: p.start # , :m
Out[3]: 0
In [4]: p.end # , :n
Out[4]: 10
In [5]: p = Pager(2)
In [6]: p.start
Out[6]: 10
In [7]: p.end
Out[7]: 20
property 속성은 두 가지 방식이 있습니다.
장식기 방식
클래스의 실례 방법에 @property 장식기 적용
Python의 클래스는 구식 클래스와 신식 클래스가 있는데 신식 클래스의 속성은 구식 클래스의 속성보다 풍부하다.
구식류
구식 클래스, @property 장식기
class Goods:
def __init__(self, name):
self.name = name
@property
def price(self):
return 100
# ipython
In [10]: g = Goods(' ')
In [11]: g.price
Out[11]: 100
신식류
신식 클래스, 세 가지 @property 장식기
class Goods:
"""
python3 object
python2、3 , python3 @xxx.setter @xxx.deleter
"""
@property
def price(self):
print('@property')
@price.setter
def price(self, value):
print('@price.setter')
@price.deleter
def price(self):
print('@price.deleter')
# ipython
In [13]: g = Goods()
In [14]: g.price
@property
In [15]: g.price = 100
@price.setter
In [16]: del g.price
@price.deleter
주의하다
# Goods @property
class Goods(object):
def __init__(self, name, price):
#
self.original_price = price
#
self.discount = 0.8
@property
def price(self):
# = *
new_price = self.original_price * self.discount
return new_price
@price.setter
def price(self, value):
self.original_price = value
@price.deleter
def price(self):
print(' ')
del self.original_price
# ipython
In [22]: g = Goods(' ', 2000)
In [23]: g.price
Out[23]: 1600.0
In [24]: g.price = 3000
In [25]: g.price
Out[25]: 2400.0
In [26]: del g.price
In [27]: g.price
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-27-38ee45b469f2> in <module>
----> 1 g.price
<ipython-input-18-d5ea66eb7ece> in price(self)
12 def price(self):
13 # = *
---> 14 new_price = self.original_price * self.discount
15 return new_price
16
AttributeError: 'Goods' object has no attribute 'original_price'
클래스 속성 방식
창설 값은property 대상의 클래스 속성입니다. 클래스 속성을 사용하는 방식으로property 속성을 만들 때 구식 클래스와 신식 클래스는 차이가 없습니다.
class Foo:
def get_bar(self):
return 'get_bar'
BAR = property(get_bar)
# ipython
In [32]: f = Foo()
In [33]: f.BAR
Out[33]: 'get_bar'
f.BAR 자동 호출 get_bar () 방법, 방법의 반환값 가져오기property () 에 네 개의 매개 변수가 있습니다
class Foo(object):
def __init__(self, bar):
self.bar = bar
def get_bar(self):
print('get_bar')
return self.bar
def set_bar(self, value):
""" """
print('set bar ' + value)
self.bar = value
def del_bar(self):
print('del bar')
del self.bar
BAR = property(get_bar, set_bar, del_bar, "bar description...")
# ipython
In [50]: f = Foo('python')
In [51]: f.BAR
get_bar
Out[51]: 'python'
In [52]: f.BAR = 'Java'
set bar Java
In [53]: f.BAR
get_bar
Out[53]: 'Java'
In [54]: del f.BAR
del bar
property 대상과 @property 장식기 비교
클래스 속성 방식은property 대상 속성을 만드는 세 가지 접근 방식을 가지고 있기 때문에 우리는 그들의 몇 가지 속성의 접근 특징에 따라 각각 세 가지 방법을 같은 속성에 대한 것으로 정의할 수 있다. 즉, 가져오기, 수정, 삭제, @property 장식기와 비교할 수 있다.
property 대상 클래스 속성
# Goods property
class Goods(object):
def __init__(self, name, price):
#
self.original_price = price
#
self.discount = 0.8
def get_price(self):
# = *
new_price = self.original_price * self.discount
return new_price
def set_price(self, value):
self.original_price = value
def del_price(self):
print(' ')
del self.original_price
PRICE = property(get_price, set_price, del_price, "price description")
# ipython
In [59]: g = Goods('Mac ', 9000)
In [60]: g.PRICE
Out[60]: 7200.0
In [61]: g.PRICE = 10000
In [62]: g.PRICE
Out[62]: 8000.0
In [63]: del g.PRICE
@property 장식기
# Goods @property
class Goods(object):
def __init__(self, name, price):
#
self.original_price = price
#
self.discount = 0.8
@property
def price(self):
# = *
new_price = self.original_price * self.discount
return new_price
@price.setter
def price(self, value):
self.original_price = value
@price.deleter
def price(self):
print(' ')
del self.original_price
# ipython
In [59]: g = Goods('Mac ', 9000)
In [60]: g.PRICE
Out[60]: 7200.0
In [61]: g.PRICE = 10000
In [62]: g.PRICE
Out[62]: 8000.0
In [63]: del g.PRICE
두 가지 모두 가능하지만 @property 장식기는 구식 클래스에 @property만 있고 @method는 없습니다.setter 및@method.deleter, 신식 클래스는 두 가지 모두 사용할 수 있습니다.그래서 여러분의 습관을 보고 하나를 고르세요.
이상은pythonproperty의 사용 기교로 공유한 상세한 내용입니다.pythonproperty에 대한 더 많은 자료는 저희 다른 관련 글에 주목하세요!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
로마 숫자를 정수로 또는 그 반대로 변환그 중 하나는 로마 숫자를 정수로 변환하는 함수를 만드는 것이었고 두 번째는 그 반대를 수행하는 함수를 만드는 것이었습니다. 문자만 포함합니다'I', 'V', 'X', 'L', 'C', 'D', 'M' ; 문자열이 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.