Make sure you removed all debugging print statements error

Chris Angelico rosuav at gmail.com
Mon Aug 8 12:20:20 EDT 2016


On Mon, Aug 8, 2016 at 10:20 PM,  <aaryanreviews at gmail.com> wrote:
> class Person(object):
>     def __init__(self, name):
>         self.name = name
>         try:
>             firstBlank = name.rindex(' ')
>             self.lastName = name[firstBlank+1:]
>         except:
>             self.lastName = name
>         self.age = None

Please don't EVER do this kind of thing. EVER. Firstly, the bare
"except:" clause should basically never be used; instead, catch a very
specific exception and figure out what you want to do here - but
secondly, don't force people's names to be subdivided.

https://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about-names/

Even if you *must* split the name like this, there are far more
Pythonic ways to do so. But I won't tell you about them, because you
shouldn't even use a concept of "lastName".

>     def getLastName(self):
>         return self.lastName

Python is not Java. You don't need a public attribute "self.lastName"
and a getter "self.getLastName()".

>     def setAge(self, age):
>         self.age = age
>     def getAge(self):
>         if self.age == None:
>             raise ValueError
>         return self.age

Same again - you don't need getters and setters. Please don't write
code like this in Python.

>     def __str__(self):
>         return self.name

Hmm, I'm not sure this is a good idea - you're treating a person as
equivalent to his/her name. Normally you'd define the repr and/or str
of a class to show exactly what thing this is; it'll make debugging
easier.

ChrisA



More information about the Python-list mailing list