0

I have a method (__init__) in a class, and I want to use a function from the class in this method.

But when I want to run my program. I get: NameError: global name 'myfunction' is not defined

Someone, who knows what I have to do? :)


Thank you. But I have still a problem, because def myFunc(self, a): is a method and I wanted a function.

3
  • 4
    Please add some code demonstrating the problem. Commented Dec 26, 2010 at 3:16
  • Maybe you are missing self? So the call should be self.myfunction(). Commented Dec 26, 2010 at 3:20
  • you say: "I have a method (init) in a class, and I want to use a function from the class in this method". Please show us the definition of this class, so we can stop guessing what you mean. Commented Dec 26, 2010 at 12:28

2 Answers 2

3
class Myclass(object):
    def __init__(self, a):
        self.a = self.myFunc(a)

    def myFunc(self, a):
        return a+1
Sign up to request clarification or add additional context in comments.

Comments

0

Then you don't have a function call in the method, but you have a method call in it. When creating a class you must specify the object when calling its methods:

>>> class A(object):
...     def __init__(self, val):
...             self.val = self._process(val)
...     def _process(self, val):
...             return val % 7
...     process = _process    #if you are outside methods then you don't
...                           #have to add "self.".
... 
>>> a = A(5)
>>> a.process(3)
3
>>> a._process(6)   #"a" is passed as the "self" parameter
6

As you can see in a class definition, but outside the methods you must specify the method name only, and not the "self.". Also you can't refer to a method not already defined:

>>> class B(object):
...     def __init__(self):pass
...     def method1(self):pass
...     __call__ = method2   #method2 not defined!
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in B
NameError: name 'method2' is not defined

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.