The following example, when executed, returns:

Traceback (most recent call last):
File "/home/des/programming/python/OOP/test.py", line 13, in ?
demonstration(6).number()
TypeError: 'int' object is not callable

The example:

class demonstration:

    def __init__(self,number):
        
        self.number = number

    def number(self):

        fiveup = self.number + 5

        print fiveup

demonstration(6).number()

Now, I know how to fix the problem, don't let variables and methods share names.

But I want to know why it does happen. I guess because the method (number) is in fact demonstrtaion.self.number() or something like it. Because the names conflict. But I'm too much of a newb to actually know. Any answers?

Recommended Answers

All 3 Replies

Here the method is demonstration.number (it's an attribute of the class, which you hide in the instances with self.number = number .

You are right as to why this is happening; a variable and a function sharing the same name.

From within the class scope, self.number is the variable and self.number() is the function. When you initialize the class, it goes through and recognizes each function then calls __init__ (at least that's how I understand it). Since init is assigning something to self.number (which is already defined as a function), the reference to this method is over-written by the value of the passed-in parameter. Why not use self._number = number ?

Ok, thanks guys. That makes sense to me.
It's an easily fixable problem once you know it exists, but I spent ten minutes trying to figure out why I was getting a type error before hand.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.