7

If I had a class with a function like the following and I wanted to have two variables that had default values:

class item:
    def __init__(self, var1=1, var2=2)
        self.var1 = var1
        self.var2 = var2

How could I create an instance of this class and change var2's value but not var1's?

a = item(#Leave var1 alone, but set var2 to 'hello')

2 Answers 2

3

You would just instantiate it like:

# leave var1 as default
a = item(var2='hello')

# leave var2 as default
a = item(var1='hey')

# overwrite both var1 and var2
a = item(var1='hey', var2='hello')

# use both defaults
a = item()

The thing to note in your example in the comment is you must now provide a var1 since it has no default. So item(var1=1, var3=2) and item(1, var3=2) would both work, while item(var3=2) would not. Also keyword arguments must come last when there are arguments without default values, so item(var3=2, 1) would also not work but item(var3=2, var1=1) would.

Sign up to request clarification or add additional context in comments.

2 Comments

What if I had def __init__(self, var1, var2=2, var3=3)? Would it be the same?
Yes, it would be the same. Try it for yourself :)
0

Use named parameters when instantiating:

a = item(var2=42)

This would leave var1 to its default value of 1, but set var2 to 42.


The following script shows this in action:

class item:
    def __init__(self, var1=1, var2=2):
        self.var1 = var1
        self.var2 = var2

a = item()
print a.var1
print a.var2

b = item(var2=42)
print b.var1
print b.var2

The output of that is, as desired:

1
2
1
42

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.