Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

haakon Guttormsen
haakon Guttormsen
2,157 Points

How to call a method within a class

I want to call the phone-method that should return a persons phonenumber. I'm not sure how to make this work. The last line should print Julie's phonenumber. Instead I get an error "phonebook has no attribute number". Any ideas on how to make this work? thanks.

class Phonebook:
    def __init__(self,name,lastname,number):
        self.name=name
        self.lastname=lastname
        self.number=number


        def number(self):
            return self.number


Julie = Phonebook('Julie', 'Jonson','45065409') 
Phonebook.number(Julie) 

2 Answers

Cooper Runstein
Cooper Runstein
11,850 Points

Here's where you're going wrong:

Phonebook.number(Julie) 

Phonebook is a class, it's just a blueprint, there is no object Phonebook, the only actual thing you've created to interact with is Julie. You can call number on Julie, but not phonebook

Julie.number()
haakon Guttormsen
haakon Guttormsen
2,157 Points

If I use the following code to print Julie's number I get an error saying that "str object is not callable".

Julie.number()

So I still don't see how to print the number using the method i've created.

Cooper Runstein
Cooper Runstein
11,850 Points

Ahh, because you've named two things 'number', both a property and a method, that won't work. You need to change one, and only call the method.