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