I have a class which essentially functions like the example below. The constructor takes two arguments, which are both defaulted to None
if no value is given. The goal of the class is that, given a value for foo
, the user can call the calculateBar()
function to calculate the value of bar
. Conversely, the user should be able to provide a value for bar
and then call the calculateFoo()
function to calculate a value for foo
. Notably, these functions are essentially the inverse of one another.
class ExampleClass:
def __init__(self, foo=None, bar=None):
self.foo = foo
self.bar = bar
# Essentially an XNOR. Raises an exception if:
# 1. Both foo and bar are 'None' (no value given for either)
# 2. Neither foo, nor bar are 'None' (value given for both)
if bool(foo == None) == bool(bar == None):
raise ValueError("Please give a value for Foo or Bar (but not both)")
def calculateFoo(self):
return self.bar / 2.0
def calculateBar(self):
return self.foo * 2.0
The issue I have is that I want to restrict the class to only allow the user to give a value for foo
OR a value for bar
, but not both, i.e. exactly one of them should hold a value, the other should be None
. My current method is to simply raise an exception in the case where either foo=None and bar=None
, or foo!=None and bar!=None
. This, however, seems like an inelegant solution. Is there a better way to restrict the user to entering just one of the two arguments, but still allow the correct use of the calculateFoo()
and calculateBar()
functions? Is there a better way to organise the class to allow what I need?