zoukankan      html  css  js  c++  java
  • Python学习札记(三十七) 面向对象编程 Object Oriented Program 8 @property

    参考:@property

    NOTE

    1.在绑定参数时,为了避免对属性不符合逻辑的操作,需要对传入的参数进行审核。

    #!/usr/bin/env python3
    
    class MyClass(object):
    	"""docstring for MyClass"""
    	def __init__(self):
    		super(MyClass, self).__init__()
    
    	def set_Attr(self, score):
    		if score >= 0 and score <= 100:
    			self.score = score
    		else:
    			raise ValueError('Attribute Setting Error')
    
    	def get_Attr(self):
    		return self.score
    
    def main():
    	A = MyClass()
    	A.score = 59
    	print(A.get_Attr())
    
    	A.set_Attr(101)
    	print(A.get_Attr())
    
    if __name__ == '__main__':
    	main()
    
    59
    Traceback (most recent call last):
      File "./oop9.py", line 26, in <module>
        main()
      File "./oop9.py", line 22, in main
        A.set_Attr(101)
      File "./oop9.py", line 12, in set_Attr
        raise ValueError('Attribute Setting Error')
    ValueError: Attribute Setting Error
    

    普通的做法是,调用对象的方法传入参数并设置,但是这样看上去又过于繁琐。

    2.Python内置的@property装饰器负责把一个方法变成属性进行调用:

    class Student(object):
    	"""docstring for Student"""
    	def __init__(self):
    		super(Student, self).__init__()
    	
    	@property
    	def score(self): # turn into an attribute
    		return self.score
    
    	@score.setter
    	def score(self, val):
    		if val >= 0 and val <= 100:
    			self.score = val
    		else:
    			raise ValueError('Attribute Setting Error')
    
    RecursionError: maximum recursion depth exceeded in comparison
    

    把一个getter方法变成属性,只需要加上@property就可以了,此时,@property本身又创建了另一个装饰器@score.setter,负责把一个setter方法变成属性赋值。

    getter => Attribute => create setter
    

    3.还可以定义只读属性,只定义getter方法,不定义setter方法就是一个只读属性:

    class Student(object):
    	"""docstring for Student"""
    	def __init__(self):
    		super(Student, self).__init__()
    	
    	@property
    	def score(self): # turn into an attribute
    		return self.score
    
    

    此时Attribute score就是一个只读属性。无法对其进行设置或赋值。

    2017/3/3

  • 相关阅读:
    SQL的增删改查
    SQL语句的分类
    创建新DB和新用户&DBeaver连接
    jQuery css() 方法:设置或返回被选元素的一个或多个样式属性
    jQuery
    jQuery
    jQuery
    jQuery
    jQuery
    jQuery
  • 原文地址:https://www.cnblogs.com/qq952693358/p/6498903.html
Copyright © 2011-2022 走看看