程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Usage of property in Python classes

編輯:Python
class Duck():
def __init__(self, input_name):
self.hidden_name = input_name
def get_name(self):
print('inside the getter')
return self.hidden_name
def set_name(self, input_name):
print('inside the setter')
self.hidden_name = input_name
name = property(get_name, set_name) # property take get_name Convert to getter Method ,set_name by setter Method 
a = Duck('hhh')
print(a.name) # Automatically called get_name, Print inside the getter And back to hhh
print(a.hidden_name) # Still directly accessible hidden_name
class Duck():
def __init__(self, input_name):
self.hidden_name = input_name
@property
def name2(self): # Another setting getter Method method 
print('inside the getter')
return self.hidden_name
@name2.setter
def set(self, input_name): # setter Method 
print('inside the setter')
self.hidden_name = input_name
a = Duck('hhh')
print(a.name2)
class Circle():
def __init__(self, radius):
self.radius = radius
@property
def diameter(self): # Convert methods to properties 
return 2 * self.radius
c = Circle(5)
print(c.diameter) # return 10
c.radius = 7
print(c.diameter) # Dynamically calculable , return 14
try:
c.diameter = 15 # Because... Is not specified in the class setter Method @diameter.setter, Therefore, you cannot set it from the outside 
except Exception as exc:
print(exc)
class Circle():
def __init__(self, radius):
self.radius = radius
self.diameter = 2 * self.radius
c = Circle(5)
print(c.diameter) # return 10
c.radius = 7
print(c.diameter) # It cannot be calculated dynamically , return 10

Reference material :《Python Language and its application 》【 beautiful 】 Lubanovic Writing


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved