[Tutor] class-inheritence

DL Neil PyTutor at danceswithmice.info
Tue May 19 14:59:04 EDT 2020


On 19/05/20 2:34 AM, shubham sinha wrote:
> Hi,
> we have" package" class that represents a software package which could be
> installed on machine on our network.
> "Repository" class that represent all the packages we have available for
> installation internally.
> In this case "Repository" is not a "package" and vice-versa. Instead of
> this 'Repository' contains "Packages"
> 
> Below given is the repository class  ->
> 
> class Repository:
> def __init__(self):
>       self.packages = {}
> def add_packages(self, package):
>       self.packages[package.name] = package
> def rem_packages(self, package):
>      del self.packages[package.name]
> def total_size(self):
>      result = 0
>      for package in self.packages.values():
>          result += package.size
>      return result


Others have covered the ground. Herewith further critique:

- always copy-paste code from your editor/command-line
[the above is missing tabs and thus immediately appears in-error]
- it would be polite to mention if this is a 'homework' assignment, 
and/or if you are working from a particular text-book or on-line course 
[to which we might refer for context/clarification]
- "rem_packages" is not a good name: just because "add" is a three 
letter word there is no reason why "remove" should not be spelled-out 
in-full
[easing readability]
- Repository is essentially a list (or, you may later prefer, a 
dict[ionary]) in which case it could be coded as a sub-class list or 
UserList
[and receive a bunch of pre-coded, powerful-stuff, 'for free']
- Python lists come with a built-in len method, but if you wish to 
maintain a different approach, might others be expecting/more used to 
seeing, len()? cf total_size()
[not that there is anything wrong with having a method with a 
better/self-documenting name to fit the context - indeed one could be 
made a synonym for the other and you'd 'inherit' (hah!) the best of both 
worlds!]


Web.Ref:
https://treyhunner.com/2019/04/why-you-shouldnt-inherit-from-list-and-dict-in-python/
-- 
Regards =dn


More information about the Tutor mailing list