Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,836 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,836 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.