1

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?

3
  • 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. Commented Dec 31, 2014 at 9:10
  • Your methods miss a self as their first argument where will the reference to the object be stored. See here. Commented Dec 31, 2014 at 9:10
  • You're right, I fixed typos in my post Commented Dec 31, 2014 at 10:06

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.