How can I call a function inside a class?

Viewed 124

I have a class in globals.py as:

#!/usr/bin/env python

class fg():                                                                                                                           
    def red(text):     return f'\033[00;49;031m{text}\033[0m'
    def heading(text): return red(text)

and I have the testrun.py script as:

#!/usr/bin/env python

from globals import fg

# Command 1:
print(fg.red("My text"))
# prints as expected


# Command 2:
print(fg.heading("My text"))
# throws the error: NameError: name 'red' is not defined

The question is how can call red function within the heading function.

3 Answers

When calling member functions you have to use the self argument, and initiate the class. So the calls would be like this.

class fg():                                                                                                                           
    def red(self, text):
        return f'\033[00;49;031m{text}\033[0m'
    def heading(self, text):
        return self.red(text)

and then

print(fg().red("My text"))
# prints as expected


# Command 2:
print(fg().heading("My text"))

First, there is a typo in your code. You misspelled return as "retrun". Also, you can't call a class method directly. Here is what you're probably looking for.

class fg():
    def __init__(self, text):
        self.text = text
    
    def red(self):
        return f'\033[00;49;031m{self.text}\033[0m'

    def heading(self):
        return self.red()

And now you can import the file.

from globals import fg

obj = fg("My text")
print(obj.red())
print(obj.heading())

I have made a lot of modifications to your code.

  1. Use self to call the class methods
  2. If the text parameter is the same for both, you need not pass it every time you call these methods. Instead, you can initialize that in the self method itself.
  3. You first need to create an object of a class to access its methods (called constructors).

First you should have init function in a class to call the class, then you should create some functions. Then you can create some static function that can be called without passing the parameters of the Class.
In Your globals.py file:

class Fg:
    def __init__(self):
        #You can place some code that you
        #want to call when this class is called
        self.text = ""

    def red(self, text):
        #The self.text will make the text usable by
        # both the functions
        self.text = text

        #Return what ever you want
        return f'\033[00;49;031m{text}\033[0m'

    def heading(self, text):
        self.text = text
        return self.red()

In your testrun.py file:

from globals import Fg

print(Fg().red("Your Text"))
print(Fg().heighlight("Your Text"))
Related