Define and call plus_2_times_4 with self, namely:

class ExampleClass():

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

    def plus_2_times_4(self,x):
        return(4*(x + 2))

    def arithmetic(self):
        return(self.plus_2_times_4(self.number))

This will work.

Answer from muskrat on Stack Overflow
🌐
Quora
quora.com › How-do-I-use-a-class-function-inside-another-class-function-in-Python
How to use a class function inside another class function in Python - Quora
Answer (1 of 8): You can add a __new__(self) function to your mango object that will return a reference to itself when the class is instantiated. [code]class mango(): def func(): a=8 b=9 return a+b # New method that will return a reference to # itself when object ...
Discussions

Call a function inside of a function inside of a class in Python - Stack Overflow
So I'm having a problem with a larger piece of code where I'm getting an error message when I'm calling a function inside of another function that is inside of a class. In the code: #Test program to More on stackoverflow.com
🌐 stackoverflow.com
Defining class functions inside class functions: Python - Stack Overflow
I have a code in which I want to defina a class function inside a class function. Here's a simpler example of what I want to do. The goal of this program is to print 4. >>> class bluh: ..... More on stackoverflow.com
🌐 stackoverflow.com
Class definition within function
Your code is not formatted correctly so it is hard to read: in Python the indentation is important, so when pasting code to reddit it's important you preserve the formatting exactly. As far as I can tell the code looks unusual but fine. You do not say what "doesnt work" means (do you get an error, does it print a different value than you expected, does nothing at all happen?) and you do not share the rest of the code that calls main or whatever doSomething is --- maybe it's actually just doSomething that has the bug that does the wrong something? More on reddit.com
🌐 r/learnpython
13
0
February 17, 2025
python - Creating a class within a function and access a function defined in the containing function's scope - Stack Overflow
Edit: See my full answer at the bottom of this question. tl;dr answer: Python has statically nested scopes. The static aspect can interact with the implicit variable declarations, yield... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Codearmo
codearmo.com › python-tutorial › object-orientated-programming-functions
Adding Functions to Python Classes | Codearmo
March 28, 2025 - Classes can be created as simply a collection of functions. The functions can be defined within the class exactly the same way that functions are normally created. In order to call these functions we need to call it from the class.
🌐
Reddit
reddit.com › r/learnpython › class definition within function
r/learnpython on Reddit: Class definition within function
February 17, 2025 -

I have a class which accesses variables defined within a main() function. I know it is conventional to define classes and functions in the global scope so I moved the class out of the function, however the nonlocal keyword doesnt work if the class isnt in the function.

def main():

gv: int = 0

class myClass:

def accessGV():

nonlocal gv

doSomething(gv)

Should I move the class outside main() ? If so, should I move gv: int to the global scope?

If I keep everything in main, what happens when main is called again? Does the class get defined again and take up lots of memory?

Top answer
1 of 2
27

That's an artifact of Python's name resolution rules: you only have access to the global and the local scopes, but not to the scopes in-between, e.g. not to your immediate outer scope.

EDIT: The above was poorly worded, you do have access to the variables defined in outer scopes, but by doing x = x or mymethod = mymethod from a non-global namespace, you're actually masking the outer variable with the one you're defining locally.

In example 2, your immediate outer scope is the global scope, so MyClass can see mymethod, but in example 4 your immediate outer scope is my_defining_func(), so it can't, because the outer definition of mymethod is already masked by its local definition.

See PEP 3104 for more details about nonlocal name resolution.

Also note that, for the reasons explained above, I can't get example 3 to run under either Python 2.6.5 or 3.1.2:

>>> def myfunc():
...     x = 3
...     class MyClass(object):
...         x = x
...     return MyClass
... 
>>> myfunc().x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in myfunc
  File "<stdin>", line 4, in MyClass
NameError: name 'x' is not defined

But the following would work:

>>> def myfunc():
...     x = 3
...     class MyClass(object):
...         y = x
...     return MyClass
... 
>>> myfunc().y
3
2 of 2
12

This post is a few years old, but it is among the rare ones to discuss the important problem of scope and static binding in Python. However, there is an important misunderstanding of the author for example 3 that might confuse readers. (do not take as granted that the other ones are all correct, it is just that I only looked at the issues raised by example 3 in details). Let me clarify what happened.

In example 3

def myfunc():
    x = 3
    class MyClass(object):
        x = x
    return MyClass

>>> myfunc().x

must return an error, unlike what the author of the post said. I believe that he missed the error because in example 1 x was assigned to 3 in the global scope. Thus a wrong understanding of what happened.

The explanation is extensively described in this post How references to variables are resolved in Python

Find elsewhere
🌐
freeCodeCamp
forum.freecodecamp.org › curriculum help
Accessing inner functions in a class - Curriculum Help - The freeCodeCamp Forum
February 4, 2022 - Hi there! I am a beginner in python so I like to experiment. I was trying object oriented programming when I got stuck on this problem. Here is my code. The problem is in the last line of code. How can I access a nested inner function using object of a class?
🌐
YouTube
youtube.com › watch
#61 Function Inside a Class | Python Tutorials for Absolute Beginners | INIT | SELF - YouTube
In this video you will get an example of how to write function inside the class and explanation around init funtion and self parameters in Python.Important L...
Published: June 30, 2022
🌐
Python.org
discuss.python.org › python help
Class and inner function - Python Help - Discussions on Python.org
October 23, 2023 - Hello everyone, I have a class, where I have a function pip which I use in function wash, but I have a problem, that the python does not know the values up and down, which I defined below. How can I do it? I just need to define them below, not in the init. Is that posiible?
🌐
Reddit
reddit.com › r/learnpython › how do i call a function from within another function in a class?
r/learnpython on Reddit: How do I call a function from within another function in a class?
February 6, 2023 -

I'm learning to work with classes and I'm trying to turn my procedural code that's working perfectly into a class with a series of functions (def) within. I ran into an error while testing though. It says "name def2 is not defined," and I'm not sure how to define it.

I wrote:

from <file> import Class
x = Class()
x.def1()
x.df

So far it works perfectly and the data table looks like what I expect. def1 only uses self as a parameter.


After def1, def2-4 all use different parameters, so I can't simply write x.def2 like I did above, otherwise it errors out because I didn't input a second parameter.

Then def5 is another function with only self as a parameter that is merely a series of procedural lines that call upon def2-4 written above. However, when I tried to run x.def5(), it errors out saying "def2 is not defined," and if I comment out the def2 part, it errors out saying "def3 is not defined" instead.

How do I define these functions so I can call upon them in a separate function within the same class?

🌐
Reddit
reddit.com › r/learnpython › why have almost every function inside a class?
r/learnpython on Reddit: Why have almost every function inside a class?
November 4, 2023 -

Hi, folks I was always wondering why certain modules would have almost every single one of their functions inside a class. What are some example benefits?

Thanks in advance.

Top answer
1 of 4
9
Because the developer is following the Object Oriented Programming model and a lot of class functions outside of objects is a code smell.
2 of 4
5
So classes can be collection of related functions bundled together collection of functions that operate on some data and maintain state. First one is simple - say I write a library that operates on strings, I put them all in a single module and with a single import you get them all. Pass your parameters and get results For second one - think I want to write a module that handles temperatures. Do i give functions that operate on celsius, fahrenheit and kelvin? Then I need 3 sets of functions and user needs to keep tract of which value is in which unit. This is where state and data with behaviour comes in. What if I save data internally, always operate in one specific unit and just give user results in whichever unit they want. My work just reduced quite a bit and it doesn't matter if I store data as C, F or K. That's not your ie user's concern. During in it you tell me the unit and when you want results, you again tell me the unit in which you want data. And my code can make you do t1 = Temp(35, 'f') t2 = Temp(48.3, 'f') t3 = (t1 + t2 - Temp(3, 'c')) * (5/3) print(t3.as_kelvin()) A datatype is introduced and along with it comes all the ease using which you can work with it. Since it's a class, just doing t3. should list out all the functions that can be called (in any decent editor or even interactive shell) plus you can do arithmetic as if it was any normal integer or float. So now data has behaviour and you don't have to do temp.add(t1, t2) which is not a big deal but it has little more mental load as compared to t1+t2 so reading and understanding code becomes a little easier.
🌐
Real Python
realpython.com › inner-functions-what-are-they-good-for
Python Inner Functions: What Are They Good For? – Real Python
2 weeks ago - This practice will allow you to access your helper functions from other parts of the current module or class and reuse them as needed. Extracting inner functions into top-level non-public functions can make your code less repetitive and more readable. This practice can produce functions that consequently apply the single-responsibility principle. In Python, functions are first-class citizens.
🌐
Reddit
reddit.com › r/learnpython › calling a method inside a class vs outside a class - why still need to specify the classname?
r/learnpython on Reddit: Calling a method inside a class VS outside a class - why still need to specify the classname?
August 1, 2021 -

This code works perfectly fine.

def hi():
    print("hi")

def __init__():
    print("ok")
    bye()
    
def bye():
    print("bye")

hi()
__init__()

>>hi
>>ok
>>bye

When I put it into a class, it doesn't.

class Msg:

    def hi():
        print("hi")

    def __init__(self):
        print("ok")
        bye() #bye is not defined
    
    def bye():
        print("bye") 

    hi()   
Msg()

>>hi
>>ok
>>NameError: name 'bye' is not defined on line 8

I can easily fix it by changing the bye() on line 8 with Msg.bye()

class Msg: 

    def hi():
        print("hi")

    def __init__(self):
        print("ok")
        Msg.bye() #solved
    
    def bye():
        print("bye")

    hi()    
Msg()

>>hi
>>ok
>>bye

My question:

  1. Why do I have to prefix bye() with Msg. when it is already inside the same shared class? All the functions are defined at the same indentation level, so I'm not sure why bye() isn't defined within __init__

  2. If I still have to prefix functions inside a class with their classname, why DON'T I have to prefix the last calls in the class from hi() to Msg.hi() instead?

Re Q2: (Yes, I know it doesn't work because Msg isn't defined until all the top level code is run, but the question still applies conceptually)