[Tutor] Need to discuss about a class that can be used to print number of vowels, consonants, uppercase and lowercase letters and spaces in a string

dn PyTutor at DancesWithMice.info
Thu Aug 19 17:44:05 EDT 2021


On 20/08/2021 05.08, Alan Gauld via Tutor wrote:
> On 19/08/2021 15:54, Manprit Singh wrote:
> 
>> class StringStats:
>>     def __init__(self, seq = ""):
>>         self.str_seq = seq
>>         self.cnt_lowercase = 0
>>         self.cnt_space= 0
>>         self.cnt_uppercase = 0
>>         self.compute_stats()
>>
>>     def compute_stats(self):
>>         for ch in self.str_seq:
>>             if ch == " ":
>>                 self.cnt_space += 1
>>             elif ch.isupper():
>>                 self.cnt_uppercase += 1
>>             elif ch.islower():
>>                 self.cnt_lowercase += 1
> 
>> !) How can i place self.compute_stats() inside __init__ without
>> placing all those instance variables that are initialized to 0.
> 
> You could put them into the compute_stats() method.
> You need to set them to zero there anyway so you might
> as well just initialize them there every time.


+1, keep things 'together' and keep usage(s) 'local' and 'close'.

Isn't there a convention/habit (or perhaps has come-across from another
language where it is a requirement) that all data-attributes should
either be defined in the class or __init__()?

(I realise that in Python we (usually) initialise value, which
(inherently) defines the attribute's type, rather than considering them
two potentially-separate steps)

I remember being 'dinged' about this by some 'checker' facility. Regret
unable to reference which one. Perhaps (only) relevant to @dataclasses?


However, why not combine both suggestions? Conflate __init__() and
compute_stats() - thus the consideration 'goes away'!

(at which time, the class vs function decision will come into stark
focus...)


To the OP:
should you decide to include any of this advice in any of your articles,
please remember, per PSF code, to pass credit. Especially as could also
mention @Alan's course materials to further benefit the reader.

Conversely, I would like to propose the original code (suitably
anonymised) as a group-coding (refactoring/TDD) exercise, for future use
at a local (learners) Python Users' Group coding evening.
-- 
Regards,
=dn


More information about the Tutor mailing list