简体   繁体   中英

TypeError: unsupported operand type(s) for +: 'function' and 'int'...Need support

The code is

class Demo():
    count = 0
    def __init__(self,name, no):
        Demo.count = Demo.count + 1
        self.name = name
        self.no = no
    def display(self):
        print(self.name)
        print(self.no)
    def count(self):
        print(Demo.count)

D = Demo('Mohan',20)
D.display()
D.count()

When I run this code, I am getting the following error message.

TypeError: unsupported operand type(s) for +: 'function' and 'int' Process finished with exit code 1

How to get rid of this error and make use of class variable?

I guess your variable (count) cannot have the same name as your method (count)

class Demo():
    number = 0
    def __init__(self,name, no):
        Demo.number = Demo.number + 1
        self.name = name
        self.no = no
    def display(self):
        print (self.name)
        print(self.no)
    def count(self):
        print(Demo.number)
D = Demo('Mohan',20)
D.display()
D.count()

Returns

Mohan
20
1

I just changed the variable name

You can make this code working just by renaming this function:

def count(self):
      print(Demo.count)

or either this variable:

count = 0

You can use _ (underscore) in your variable or function name to avoid collisions.

It's all about naming so when you try to add function + 1 Python interpreter raises error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM