python property의 사용 기교 공유

9272 단어 pythonproperty

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 장식기를 추가한다.그리고 self 매개 변수가 하나밖에 없습니다
  • 호출 시 괄호 () 가 필요 없습니다
  • 인스턴스 방법: c.get_area()
    property 장식 방법: c.area

    구체적인 실례


    어떤 상점에 컴퓨터 호스트의 목록 페이지를 표시할 때 매번 요청할 때마다 데이터베이스에 있는 모든 내용을 페이지에 표시할 수 없고 페이지의 기능을 통해 부분적으로 표시하기 때문에 데이터베이스에 데이터를 요청할 때 표시할 지정은 m조에서 n조까지의 모든 데이터를 가져오는 기능을 포함한다.
  • 사용자가 요청한 현재 페이지와 총 데이터 갯수에 따라 m와 n을 계산합니다
  • 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를 적용합니다
  • 클래스 속성: 클래스에서property 대상으로 정의된 클래스 속성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
  • g.price는 @property 수식을 자동으로 실행하는price 방법을 단독으로 호출하고 방법의 반환값을 가져옵니다
  • g.price = 100개의 값이 @price를 자동으로 실행합니다.setter 수식의price 방법, 그리고 100 값을 방법의 매개 변수에 부여합니다
  • del g.price 삭제 자동 실행 @price.deleter 수식의price 방법
  • 주의하다

  • 구식 클래스의 속성은 단지 하나의 접근 방식일 뿐, @property에 의해 수식되는 방법에 대응한다
  • 신식 클래스의 속성은 세 가지 접근 방식이 있는데 각각 @property, @ 방법명에 대응한다.setter,@ 메서드 이름.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 () 에 네 개의 매개 변수가 있습니다
  • 첫 번째 매개 변수는 방법명, 호출 대상이다.속성 시 실행 방법을 자동으로 터치합니다
  • 두 번째 매개 변수는 방법명, 호출 대상이다.속성 = XXX 시 자동으로 실행 방법을 터치합니다
  • 세 번째 매개 변수는 방법명으로del 대상을 호출합니다.속성 시 실행 방법을 자동으로 터치합니다
  • 네 번째 매개 변수는 문자열, 호출 대상이다.속성.__doc__ ,이 매개 변수는 이 속성의 설명 정보입니다
  • 
    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에 대한 더 많은 자료는 저희 다른 관련 글에 주목하세요!

    좋은 웹페이지 즐겨찾기