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.
Use self to call the class methods
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.
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
Hi I'm a newbie in python programming. Please help me with this problem in python3:
pack.py
class one:
def test(self):
number = 100 ######I want to access this value and how?
print('test')
class two:
def sample(self):
print('sample')
another.py
from pack import *
class three:
def four(self):
obj = one()
print(obj.test())
###### I want to access the number value in this file and i don't know how #######
obj = three()
obj.four()
Here is an alternative
pack.py
class One:
def __init__(self):
self.number = 100
def test(self):
print('test')
class Two:
def sample(self):
print('Sample')
another.py
from pack import *
class Three:
def four(self):
self.obj = One().number
return self.obj
three = Three().four()
print(three)
By what seems to be your approach, you were using classes to access variables. It is better to instantiate variables in a constructor ( init method in class One). Then import the class and access it in another class of another file.
Also, it is a good practice to name classes beginning with uppercase letters. There are more possible ways but hope it helps.
number needs to be in a global scope, that means outside of a function definition (it shouldn't be indented)
if the variable is inside a function it is impossible to get it in another file
pack.py
number = 100
def test():
test.other_number = 999 # here we assigne a variable to the function object.
print("test")
another.py
import pack
pack.test()
print(pack.number)
print(test.other_number) # this only works if the function has been called once
Alternatively if you are using classes:
pack.py
class Someclass():
other_number = 999 # here we define a class variable
def __init__(self):
self.number = 100 # here we set the number to be saved in the class
def test(self):
print(self.number) # here we print the number
another.py
import pack
somclass_instance = pack.Someclass() # we make a new instance of the class. this runs the code in __init__
somclass_instance.test() # here we call the test method of Someclass
print(somclass_instance.number) # and here we get the number
print(Someclass.other_number) # here we retrieve the class variable
I'm looking to pass a variable out of a class and into another. To do so, I am returning the variable in a method and calling that method in another class. Unfortunately when I do so, all I get is:
<function body.returntheline at 0x7f9444673bf8>
My code is as follows:
from tkinter import *
class body:
def __init__(self):
root = Tk()
self.input_file = Entry(root)
self.input_file.pack(side = LEFT)
self.launch = Button(root, text = "Go External", command = operator)
self.launch.pack()
self.launchx= Button(root, text = "GO", command = self.testingvalue)
self.launchx.pack()
root.mainloop()
def testingvalue(self):
thesillyvalue = self.input_file.get()
print(thesillyvalue)
def returntheline(self):
test = str(self.input_file.get())
return test
class operator:
def __init__(self):
self.textvar = body.returntheline()
print(self.textvar)
if __name__ == "__main__":
body()
What is it that I have to do to get the specific value from this class instead of the function object? To test that the value does work, I have set up an internal method which does the same thing, only within the class. It does print out a string object to the console, so I am at a loss as to why the returned one does not.
You will need to pass the instance itself over to the external class via lambda or similar:
# under class body, change self.launch to this:
self.launch = Button(root, text = "Go External", command = lambda x=self: operator(x))
# Then under class operator:
class operator:
def __init__(self, body_instance): # pass in the instance of body as argument
self.textvar = body_instance.returntheline() # directly call the instance method over the instance.
print(self.textvar)
The lambda basically ensures you will always pass self (the instance) over to the external class.
But in this case the instance of the external class operator is just wasted after calling the __init__, but perhaps your real life example have a better use...
Hi everyone i wanna use a calculated value from a method of the class itself for the rest of the class methods but it must calculate once for all and i need to invoke method inside the class itself i write an example:
class something():
def __init__():
pass
def __sum(self, variable_1, variable_2):
self.summation = sum(variable_1, variable_2)
# I need to calculate summation here once for all:
# how does the syntax look likes, which one of these are correct:
something.__sum(1, 2)
self.__sum(1, 2)
# If none of these are correct so what the correct form is?
# For example print calculated value here in this method:
def do_something_with_summation(self):
print(self.summation)
Something like this seems to be what you're looking for:
class Something:
def __init__(self):
self.__sum(1, 2)
def __sum(self, variable_1, variable_2):
self.summation = sum(variable_1, variable_2)
Not saying this is the ideal approach or anything, but you haven't really given us much to go off of.
In general, make sure self is the first argument in all class methods, and you can call that class method at any time using either self.method_name() if you are using it from within another class method or instance.method_name() if you're using it externally (where instance = Something()).
Assuming that you would receive variable1 and variable2 when you instantiate the class one solution could be:
class something():
def __init__(self, variable1, variable2):
self.summation = variable1 + variable2
def do_something_with_summation(self):
print(self.summation)
If instead you're creating variable1 and variable2 inside other methods, then you could make them class variables:
class Something():
def __init__(self):
#Put some initialization code here
def some_other_method(self):
self.variable1 = something
self.variable2 = something
def sum(self):
try:
self.summation = self.variable1 + self.variable2
except:
#Catch your exception here, for example in case some_other_method was not called yet
def do_something_with_summation(self):
print(self.summation)
I've been looking here in the forum to try to find an answer and the most similar I found was this: Python: How to call class method from imported module? “Self” argument issue . But it does not solve my problem.
I have 2 script: 1- X and 2-Y. I need to import some def () from Y to X and here's my code where I import and instantiate:
X Script - it I have a variable called txtCorpus which is the one I intend to manipulate
import Y
from Y import PreProcessing
txtCorpus
def status_processing(txtCorpus):
instance = PreProcessing() #Here is where to instantiate the class contained within the Y script and where it has some defs that I need
myCorpus = instance.initial_processing(txtCorpus)
#After some other lines of operation ...
if __name__ == "__main__":
status_processing(txtCorpus)
Now the Script Y
class PreProcessing():
#property
def text(self):
return self.__text
#text.setter
def text(self, text):
self.__text = text
tokens = None
def initial_processing(self):
#Operations
When I execute the way it is there, the following error is shown:
TypeError: initial_processing() takes exactly 1 argument (2 given)
When I do this myCorpus = instance.initial_processing() , the following error is shown:
AttributeError: PreProcessing instance has no attribute '_PreProcessing__text'
What is the way I have to instantiate for the code to work when I pass txtCorpus as a parameter?
You don't include a complete exampl, but the error you're seeing here TypeError: initial_processing() takes exactly 1 argument (2 given) is because you define initial_processing as such:
def initial_processing(self):
Which only takes 1 argument (the class instance). Then, you pass it two arguments (the instance, and txtCorpus):
myCorpus = instance.initial_processing(txtCorpus)
Think of class methods like this:
instance.initial_processing(txtCorpus)
# equivalent to
initial_processing(instance, txtCorpus)
So you pass 2 arguments but only define the method to process 1. Hence, you need to define it to take two arguments:
def initial_processing(self, txt):
# code here
The error is that when defining you need to put in 2 arguments, one for self and one for txtCorput
def initial_processing(self, txt):
# Operations
Y file:
class PreProcessing():
#property
def text(self):
return self.__text
#text.setter
def text(self, text):
self.__text = text
tokens = None
def initial_processing(self, corpus):
# Operations
There is nothing wrong with your X script (except that you are importing Yclass not PreProcessing ^^)
Looks like the issue is that your function is not a part of the class you think it is. You should indent it so that it is a part of the class, and add an argument for it to accept (the txtCorpus).
class PreProcessing():
def __init__(self):
self.__text = None
#property
def text(self):
return self.__text
#text.setter
def text(self, text):
self.__text = text
tokens = None # Not sure what this is for...?
def initial_processing(self, txt):
#Operations
I'm using Python and I have two classes. I want to import a function for a class but with the ability of adding things to that function.
class Main(self):
def __init__(self):
thingstodo()
def function(self, keypressed):
#LOTS OF CODE
keyname = keypressed
if keyname = "Escape":
dosomething()
class Main2(Main):
def __init(self):
Main.__init__(self)
def function(self, keypressed):
Main.function(self, keypressed)
if keyname = "control":
dootherthing()
Basic principles
You cannot access local variables from one function (or method) in another function. This is by design.
This class Main(self): is wrong. In Python 3 do class Main:. While using self as the name of the first argument in method is a strong convention, self is just an ordinary name not a reserved keyword or built-in.
There are several problems here:
def __init(self):
Main.__init__(self)
a. The method name needs to __init__() not __init.
b. Don't hardwire the name of the parent class with Main.__init__(self) use super().__init__().
c. If you don't do anything extra in the __init__() of Main2, than you don't need to implement the __init__() at all.
Possible solution
For your problem, using a dictionary with the key press names as keys and the functions for the actions as values seems useful.
First define a few small helper functions:
def thingstodo():
print('thingstodo')
def dosomething():
print('something')
def dootherthing():
print('dootherthing')
Now your main class:
class KeyAction: # Python 3
def __init__(self):
thingstodo()
self.key_actions = {'Escape': dosomething}
def handel_key_press(self, keypressed):
#LOTS OF CODE
keyname = keypressed
func = self.key_actions.get(keyname)
if func is not None:
func()
Names are important, therefore I use KeyAction instead of Main.
This line self.key_actions = {'Escape': dosomething} is the core of this solution. Here self.key_actions is a dictionary that maps names of key press events to functions. Note dosomething without the () because I put the function object into the dictionary rather than calling this function.
Calling this function is a bit different:
func = self.key_actions.get(keyname)
if func is not None:
func()
I use the get() method of the dictionary. This returns the value for the key if the key is in it and None if not. Now func holds either a reference to the function dosomething if the key was Escape or None. If it is a function I call it with func().
An alternative here could be a try-except:
def handel_key_press(self, keypressed):
#LOTS OF CODE
keyname = keypressed
try:
self.key_actions[keyname]()
except KeyError:
pass
Now, in your child class, you only need to add another key-value pair to self.key_actions to extend its functionality:
class ExtendedKeyAction(KeyAction):
def __init__(self):
super().__init__()
self.key_actions['control'] = dootherthing
Make two instances and test your code:
key_action = KeyAction()
key_action.handel_key_press('Escape')
key_action.handel_key_press('undefined')
extended_key_action = ExtendedKeyAction()
extended_key_action.handel_key_press('Escape')
extended_key_action.handel_key_press('control')
extended_key_action.handel_key_press('undefined')
prints:
thingstodo
something
thingstodo
something
dootherthing