0

I would like to know what is the cleanest way to attain this in python:

class A():
    def __init__(self, def_val):
        self.def_val=def_val
    def ciao(self, parameter=self.def_val):
        print(parameter)

Of course the above gives me: "NameError: name 'self' is not defined"

Federico Dorato
  • 710
  • 9
  • 27

1 Answers1

3

I think that the solution is this:

class A():

    def __init__(self,def_val):
        self.def_val=def_val

    def ciao(self, parameter=None):
        if parameter is None: parameter = self.def_val
        print(parameter)

It works, and is probably the most pythonic way

In  [1]: a=A("Hi")

In  [2]: a.ciao("ehi")
Out [2]: 'ehi'

In  [3]: a.ciao()
Out [3]: 'Hi'
Federico Dorato
  • 710
  • 9
  • 27
  • Use [`is None`](https://stackoverflow.com/questions/3257919/what-is-the-difference-between-is-none-and-none) instead? – TrebledJ Jan 10 '19 at 16:15
  • 2
    You assigned the instance (normally named `self`) to `self.def_val`, without defining `self` in `__init__`. Are you missing an argument there? I know you forgot to include it in your question, but your code shoud at least be tested to produce correct output. The `Hi` returned in `Out [3]` would in reality need to be `'Hi'`, for example. – Martijn Pieters Jan 10 '19 at 16:16
  • 1
    Next, when testing for `None`, use `is None`, not `==`. – Martijn Pieters Jan 10 '19 at 16:17
  • @MartijnPieters thanks a lot! About the "self" missing, in my code I saw that and I corrected that, but here on SO, I forgot it, sorry. Thanks also for the tip about the string returned – Federico Dorato Jan 10 '19 at 16:31
  • @MartijnPieters I disagree a little about your duplicate, as that question is bot kinda useless (why would you use an attribute inside the init function when you usually set the attribute INSIDE the init function) and not so clear to read (while the answer given to it is what would have helped me) – Federico Dorato Jan 10 '19 at 16:37