开发者

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


  1. self.__variable is an instance variable, not a class variable.
  2. 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 to None and adding if arg is None: arg = real_default to the function body, does work).
  3. 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.`

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜