Passed an object instead of object's property?

54 views Asked by At

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.

1

There are 1 answers

2
swehren On BEST ANSWER

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}")