If you want to handle errors and add information, you can do it as follows:
farm = farms[0]
try:
print farm.stock
except AttributeError:
raise AttributeError("{} has no attribute 'stock'".format(farm.name))
However, it would be wiser to add an empty stockin __init__to avoid this error.
except, ( !) , try , . try, :
try:
print farm.stock["hay"]
except AttributeError:
raise AttributeError("{} has no attribute 'stock'".format(farm.name))
except KeyError:
raise KeyError("{} has no 'hay' in 'stock'".format(farm.name))
( , self.stock __init__ if "hay" in farm.stock: .)
, , , . -:
def some_func(*args, **kwargs):
try:
except:
raise Exception("Something went wrong in some_func().")
, .
AttributeError class, :
class Facility(object):
def __init__(self, ...):
...
def __getattr__(self, key):
"""Called on attempt to access attribute instance.key."""
if key not in self.__dict__:
message = "{} instance '{}' has no attribute '{}'."
message = message.format(type(self).__name__,
self.name, key)
raise AttributeError(message)
else:
return self.__dict__[key]
>>> farm = Facility("pig farm")
>>> print farm.stock
...
"AttributeError: Facility instance 'pig farm' has no attribute 'stock'."
, :
class ProtectedAttrs(object):
def __init__(self, name):
self.name = name
def __getattr__(self, key):
...
class Facility(ProtectedAttrs):
def __init__(self, name):
super(Facility, self).__init__(name)
self.animals = []
. , - .