Using class variable as non-default argument in python
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 __ini开发者_如何学Pythont__(self):
self.__variable = 6
def b(self, value = self.__variable):
print value
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
self.__variableis an instance variable, not a class variable.- Because default arguments are evaluated at
functionmethod definition time, you can't use an instance variable as default argument - at least not directly (the usual trick, defaulting toNoneand addingif arg is None: arg = real_defaultto the function body, does work). - Leading double underscores don't mean "private", they mean "name mangling and asking for trouble". If you don't know exactly what I mean, you shouldn't be using this "feature" at all. The intended use is not private members - use one underscore for that.
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.`
加载中,请稍侯......
精彩评论