Home  >  Article  >  Backend Development  >  Python uses the decorator @property to turn a method into a property instance

Python uses the decorator @property to turn a method into a property instance

高洛峰
高洛峰Original
2017-03-26 18:44:271460browse

This article mainly introduces in detail how Python uses the decorator @property to turn a method into a feature instance. Interested friends can refer to it

# -*- coding: utf-8 -*-
"""
Created on Sun Nov 13 23:19:03 2016
 
@author: toby
"""
#知识点:用装饰器@property,把方法变成一个特性
 
class Province:
    memo = 'One of China\'s 23 provinces' #静态字段
     
    def __init__(self,name,capital,leadership):
        self.Name = name #动态字段
        self.Capital = capital #动态字段
        self.Leadership = leadership #动态字段
         
    def sports(self): #定义一个动态方法,类不能访问动态方法
        print self.Name + 'The sports meeting'
     
    #把方法变成一个特性
    @property #自带的装饰器
    def Bar(self):
        print self.Name
        return 'somthing' #也是可以有一个返回值的
         
#实例化两个对象,对象名分别是:hb、sd
hb = Province('hebei','shjiazhuang','liyang')
sd = Province('shandong','jinan','angshenghui')
 
#通过对象访问这个属性,把方法的访问形式变成访问字段的访问形式
print hb.Bar

The above is the detailed content of Python uses the decorator @property to turn a method into a property instance. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn