Reputation: 8991
is there a way to keep a private class variable within the class and still use it as the default value to a non-default variable (without defining that value before, outside of the class)?
example:
class a:
def __init__(self):
self.__variable = 6
def b(self, value = self.__variable):
print value
Upvotes: 8
Views: 2469
Reputation: 70984
It's worth adding to this that you can create a custom sentinal value that doesn't get used for any other purpose in your code if you want None
to be in the range of allowable arguments. Without doing this, value
, None
can never be returned from b
.
UseDefault = object()
# Python 3? Otherwise, you should inherit from object unless you explicitly
# know otherwise.
class a:
def __init__(self):
self._variable = 6
def b(self, value=UseDefault):
if value is UseDefault:
value = self._variable
print value
Now None
can be passed to b
without causing the default to be used.`
Upvotes: 4
Reputation:
self.__variable
is an instance variable, not a class variable.None
and adding if arg is None: arg = real_default
to the function body, does work).Upvotes: 4
Reputation: 526523
You're overthinking the problem:
class a:
def __init__(self):
self.__variable = 6
def b(self, value=None):
if value is None:
value = self.__variable
print value
Upvotes: 14