xxxxxxxxxx
class MyClass:
def __init__(self):
self._my_variable = None
@property
def my_variable(self):
return self._my_variable
@my_variable.setter
def my_variable(self, value):
self._my_variable = value
# Usage:
obj = MyClass()
obj.my_variable = 10 # Setter
print(obj.my_variable) # Getter
xxxxxxxxxx
class Car():
def __init__(self):
self._seat = None
@property # getter
def seat(self):
return self._seat
@seat.setter # setter
def seat(self, seat):
self._seat = seat
c = Car()
c.seat = 6
print(c.seat)
xxxxxxxxxx
class Student:
def __init__(self, name, ssn):
self.name = name
self.ssn = ssn # Does not need to include an underscore
@property # This is the "getter" method
def ssn(self):
return "XXX-XX-" + self._ssn[-4:] # Notice the underscore
@ssn.setter # This is the "setter" method
def ssn(self, new_ssn):
if len(new_ssn) == 12:
# Add things such as data validation, operations on other attributes, etc.
self._ssn = new_ssn # Notice the underscore
@ssn.deleter # This is the "disposer" method
def ssn(self):
raise AttributeError("Can't delete SSN") # Can perform clean up, soft delete, raise exception
def __getattr__(self, name):
print(f"""{name} does not exist""")
def __setattr__(self, name, value):
if isinstance(value, str): # Check if value is a string,
print(f"Setting {name} = {value}")
self.__dict__[name] = value # set the attribute using the __dict__ attribute
else: # Otherwise, raise an exception noting an incorrect data type
raise Exception("Unexpected data type!")
shaw = Student("Daniel Shaw", "193-80-1821")
print(shaw.ssn) # calling the "getter"
shaw.ssn = "821-11-9380" # calling the "setter"
del shaw.ssh # calling the "deleter"
xxxxxxxxxx
class Protective(object):
"""protected property demo"""
#
def __init__(self, start_protected_value=0):
self.protected_value = start_protected_value
#
@property
def protected_value(self):
return self._protected_value
#
@protected_value.setter
def protected_value(self, value):
if value != int(value):
raise TypeError("protected_value must be an integer")
if 0 <= value <= 100:
self._protected_value = int(value)
else:
raise ValueError("protected_value must be " +
"between 0 and 100 inclusive")
#
@protected_value.deleter
def protected_value(self):
raise AttributeError("do not delete, protected_value can be set to 0")
xxxxxxxxxx
class Person:
# Constructor
def __init__(self, name, age):
# Since we making getters and setters, we should mangle the varible names to make them "private" by adding 2 underscores.
self.__name = name
self.__age = age
# Getters
def get_name(self):
return __self.name
def get_age(self):
return __self.age
# Setters
def set_name(self, new_name):
self.__name = new_name
def set_age(self, new_age):
self.__age = new_age
xxxxxxxxxx
class A():
"""Defines a class A with x and y attribute"""
def __init__(self, x, y):
"""Every instance of A has x and y attributes"""
self.__x = x #private instance attribute x
self.__y = y #private instance attribute y
def GetX(self):
"""Retrieves the x attribute"""
return self.__x
def GetY(self):
"""Retrieves the y attribute"""
return self.__y
def SetX(self, x):
"""sets the x attribute"""
self.__x = x
def SetY(self, y):
"""sets the y attribute"""
self.__y = y
xxxxxxxxxx
class TreasureBoX:
def __init__(self, treasure="Nothing Valueable Inside"):
self._treasure = treasure
@property
def get_treasure(self):
print(f"The TreasureBoX contains {self._treasure}")
return self._treasure
def set_treasure(self, treasure):
if isinstance(self._treasure, str):
self._treasure = treasure
else:
print("Not a Valid Treasure")
print(f"The TreasureBoX contains {self._treasure}")
obj = TreasureBoX()
treasure = obj.get_treasure #we don't need () cause we used @property decorator
obj.set_treasure("Diamond")
try:
obj.set_treasure(10) # This will print "Not a Valid Treasure"
except Exception as e:
print(f'Invalid treasure getting error{e}')