-3

I have the following script in a python file classfile.py

class Myclass:
    def testadd(x,y):
           return x+y

In another python file callfile.py

from classfile import Myclass
print testadd(3, 5)

while running the script callfile.py, I am getting

NameError: name 'testadd' is not defined

What's wrong with my code?

Cyclonecode
  • 29,115
  • 11
  • 72
  • 93
Prabhakar
  • 1,138
  • 2
  • 14
  • 30

2 Answers2

2

you can define the method as a "classmethod":

#!/usr/bin/python
class Myclass():
   @classmethod
   def testadd(cls, x, y):
       return x + y

Then you can use it in this way:

#!/usr/bin/python
from classfile import Myclass

print Myclass.testadd(3, 5)

without using the "classmethod" decorator you can only use it in this way:

#!/usr/bin/python
from classfile import Myclass

aclass = Myclass()
print aclass.testadd(4, 5)
SuperBiasedMan
  • 9,814
  • 10
  • 45
  • 73
Marvix
  • 36
  • 3
1

You can use something like this.

classfile.py

class MyClass:
    def testadd(self, x, y):
        self.x = x
        self.y = y 
        return x+y

callfile.py

import classfile
ob = classfile.MyClass()
print ob.testadd(21,3)
Vinay Ranjan
  • 294
  • 3
  • 14