Problem: I'm creating a class with attributes. Some of them should be only readable and some should be completely inaccessible when trying to print them out. I'm trying to achieve it through __setattribute__
and __getattribute__
functions (I just couldn't think of a better way to do that, if you have any suggestions on how to improve this, I would greatly appreciate it). The problem is that while __getattribute__
function works perfectly fine and raises needed exception, the __setattribute__
doesn't. The program simply passes it.
Code:
class Fruit:
def __setattribute__(self, name, value):
if name in ('exp_date'):
raise AttributeError('Unable to edit')
return __setattribute__(self, name, value)
def __getattribute__(self, name):
if name in ('subtype'):
raise AttributeError('Unable to view this object')
return __getattribute__(self, name)
def __init__(self, sub:str = None, col:str = None, expd:int = None, pkp:int = None, amount:int = None):
self.color, self.price_per_kilo = col, pkp
self.amount = amount
self.exp_date = expd
self.subtype = sub
def estimaterevenue(self):
return self.price_per_kilo * self.amount
Test:
fruit= Fruit()
fruit.exp_date = 123 # __set__ is being passed for some reason
print(fruit.subtype) # AttributeError: Unable to view this object