Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I call a function inside a class?

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.

like image 622
nino Avatar asked Dec 02 '25 06:12

nino


2 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"))
like image 191
Niteya Shah Avatar answered Dec 03 '25 18:12

Niteya Shah


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).
like image 28
Dhyey Shah Avatar answered Dec 03 '25 20:12

Dhyey Shah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!