[Tutor] class-inheritence

Mats Wichmann mats at wichmann.us
Mon May 18 16:24:38 EDT 2020


On 5/18/20 8: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
> 
> My problem:
> I am unable to define or call package class by which repository class will
> contain package class.
> Please help me through this as this is the example given to me by those who
> taught me class inheritance in which one class have relation with other but
> one class is not child/inherit to other.
> Guide me through this so that i can think clearly regarding to object
> oriented programming problems.


This looks okay conceptually.   You're implementing "composition" by
letting Repository "have a" Package - you're storing those in a
dictionary "packages" where the key is the package name and the value is
the Package instance.

Can you say more about what isn't working out for you?

Your Package class should have attributes describing details of a
package - name, version, architecture (ia32 vs x64 vs arm), description,
etc. You might need more or less of those.

===

Going a bit beyond your question:

Might observe that as written, you have a "last name wins" policy,
whereas you might want to do some validation - like perhaps complaining
if a pkg name is seen a second time, since names have to be unique as
they're used as the key.

That is, for a trivial case:

class Package:
    def __init__(self, name, arch='noarch'):
        self.name = name
        self.arch = arch

repo = Repository()
repo.add_package(Package("qemu-system", "686"))
repo.add_package(Package("qemu-system", "x86_64"))

the second overwrites the first, because this method doesn't care if
it's already in self.packages:

def add_packages(self, package):
     self.packages[package.name] = package



More information about the Tutor mailing list