0

I use Python 3 and I have small problem with kwargs. Is it possible to use instance attributes as a default argument value? I mean something like this:

class foo:
    def __init__(self, a,b):
        self.a = a
        self.b = b

    def setNewA(self, a=self.a):
        print(a)

But I've got an error:

NameError: name 'self' is not defined

If I use class name I've got:

AttributeError: type object 'foo' has no attribute 'a'

I know that the other method is to use something like this:

    def setNewA(self, a=None):
        a = a or self.a
        print(a)

But maybe there is some way to do it?

voldi
  • 423
  • 2
  • 4
  • 10
  • You are missing the `self` parameter from both method definitions. And no, you can't use an instance attribute as a default argument; they don't exist when the method is created. – jonrsharpe Dec 31 '14 at 09:10
  • Your methods miss a `self` as their first argument where will the reference to the object be stored. See [here](https://docs.python.org/3/tutorial/classes.html#method-objects). – zegkljan Dec 31 '14 at 09:10
  • You're right, I fixed typos in my post – voldi Dec 31 '14 at 10:06

1 Answers1

0

Not sure if this fits your use-case, but how about this?

>>> class foo:
...    b = 1
...
...    def setNewA(self, a=b):
...        print(a)
>>> 
>>> f = foo()
>>> f.setNewA()
1
>>> f.setNewA(2)
2
Pankaj Parashar
  • 9,762
  • 6
  • 35
  • 48