0

There is two classes - Company and Project. Company object has property projects as list, that should indicate list of Project instances that is added to the company Here is realization of classes and methods to add projects to the company:

class Company(object):
def __init__(self, companyname):
    self.companyname = companyname
    self.projects = list()

def show_projects(self):
    print(f"Company projects: {self.projects}")

def add_project(self, name):
    return self.projects.append(Project(name))


class Project(object):
    def __init__(self, name):
        self.name = name

But when I try to initialize company, then project and add it to company, add add_project returns not project.name, but object itself, so i.e. output of this:

firm = Company("New")
first = Project("first")
print(first.name)
firm.add_project(first.name)
firm.show_projects()

will be:

first
Company projects: [<__main__.Project object at 0x00A54170>]

Why is it passing not name, but object itself? Can't find out what is missing here.

martineau
  • 119,623
  • 25
  • 170
  • 301
  • Because `self.projects` is a list of Project objects. When you call `Project(Name)`, it creates and returns a new instance of `Project`. If you want the name, you should do `map(lambda x: x.name, self.projects)` and print that. – CJR Nov 07 '18 at 19:34
  • 1
    Because you call `self.projects.append(Project(name))` – Brad Solomon Nov 07 '18 at 19:34
  • well, it might be a problem in thise calling as well:D this may be rewritten to pass objet property .name instead of whole object of Project class? – Назарій Кушнір Nov 07 '18 at 19:54

1 Answers1

1

firm.projects is a list so in show_projects when you print it it will be a list of objects. One solution would be to modify show_projects to format the list into a comma separated string first:

def show_projects(self):
    formatted_projects = ','.join([p.name for p in self.projects])
    print(f"Company projects: {formatted_projects}")
swehren
  • 5,644
  • 1
  • 17
  • 11