1

For example:

class student():
    def __init__(self, name, pref_name=None):
        self.name = name
        self.pref_name = pref_name if pref_name else name

bob = student('robert')
print("Bob name:", bob.name)
print('Bob preferred name:', bob.pref_name)

Can this be made any shorter and easier to read?

def __init__(self, name, pref_name=name) 

unfortunately does not work.

Ben Quigley
  • 727
  • 4
  • 18
  • No, your first sample is a canonical way for doing it. – Łukasz Rogalski Oct 23 '16 at 17:44
  • One problem with the longer version is that it doesn't allow me to create students whose preferred name is actually None (obviously not the case with any real students that I know of, but I do want to do this with the actual Python class I'm working on) – Ben Quigley Oct 23 '16 at 17:45
  • nit: You don't need `()` in your class declaration. – idjaw Oct 23 '16 at 17:47
  • 1
    @Iroh You can work around that by using a sentinel different from `None`. For example: `sentinel = object(); def __init__(self, name=sentinel): if name is sentinel: ...`. This is one of the very few cases in which using `is` is idiomatic python. – Bakuriu Oct 23 '16 at 17:48

0 Answers0