[Tutor] class-inheritence

Alex Kleider akleider at sonic.net
Mon May 18 15:38:09 EDT 2020


On 2020-05-18 07:34, 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.
> ----------------------------------------

The following might help get you going until the more expert tutors 
chime in.
(I offer this since they generally are pretty quiet week ends.)

"""
You must indent all that defines your classes.
I suggest you delete the ending 's' in the names of
your add and remove methods since you are removing
single packages not groups there of.
The 'for' loop in total_size needed a bit of a rewrite.
What follows works. rem_package not tested.
"""

class Package(object):
     def __init__(self, size, name):
         self.size = size
         self.name = name
     def __repr__(self): # I added this to help with debugging.
         return("package.size: {}, package.name: {}"
             .format(self.size, self.name))

class Repository(object):
     def __init__(self):
          self.packages = {}
     def add_package(self, package):
          self.packages[package.name] = package
     def rem_package(self, package):
         del self.packages[package.name]
     def total_size(self):
         result = 0
         for key in self.packages:
             result += self.packages[key].size
         return result

p1 = Package(3, 'p1')
p2 = Package(5, 'p2')

r = Repository()

r.add_package(p1)
r.add_package(p2)
print("total size of repository is {}."


More information about the Tutor mailing list