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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With