Sorry, Im new to Python and have a basic q
I have 2 python files
FileA.py
Class ABC:
def __init__(self, loggingLevel = 20):
self.data = None
logging.basicConfig(level=loggingLevel)
pass
def asd(self, text)
*
*
if __name__ == '__main__':
X=ABC(10)
Y=X.asd(text)
I have another file FileB.py from where i want to call function asd. I have the parameter 'text' to pass, but what should i pass for parameter 'self'. tried many options , but when it goes to File A, its failing as the value of self is not correct
self is implicitly passed if you have a reference to an instance of the containing class. In other words, you can do the same thing that you did in main in the FileB.py:
FileB.py
from FileA import ABC
X = ABC(10)
Y = X.asd(text)
Related
I've searched a lot about how to reuse a method from a class in the main.py file. i got some similar and basic solutions but in my case is a bit different.
/lib/module.py
class Myclass:
def __init__(self, x):
self.thisX = x
def check(self):
if self.thisX == 2:
print("this is fine. going to print it")
self.printing()
# this method will use in this class and must use from the main.py
# the parameter "z" is gonna use only when the method will call from main.py
def printing(self, z):
if z == 1 :
print("we got ", z)
else:
print(self.x)
/main.py
from lib.module import Myclass
# this is how i use the check() method once in my main.py
Myclass(2).check()
# the Myclass() gets "2" only once at the beginning of the program...
# i don't wanna pass "2" to the Myclass() everytime that i wanna use the printing() method...
c = Myclass()
c.printing(1)
error
TypeError: __init__() missing 1 required positional argument: 'x'
testing:
if i don't use the def init(), everything will be fine. but the problem is i need to keep it
This line in main.py:
c = Myclass()
Calls this function:
class Myclass:
def __init__(self, x):
self.thisX = x
Every time you create an instance of Myclass it will call the __init__() function. You declared it to take 2 arguments: self and x. self is always passed implicitly because it's a class, but you need to give it an argument 'x'.
So you can change main.py to this for example:
c = Myclass(2) # here x = 2
c.printing(1)
Please read this for more information
Also, in general, class names are written in CapWords style so it's a good idea to call your class MyClass instead of Myclass
Edit:
Since you don't want to pass x to __init__() and you want to set x from main.py you can try something like this:
class Myclass:
x = 0
def check(self):
if self.x == 2:
print("x is 2")
from main.py you can do:
Myclass.x = 2; #this only needs to be done once
Myclass().check()
Output:
x is 2
I think #richflow 's answer hit the point. If some variable is to be shared by all instances of a class, it's logical to assign its value using Myclass.x = new_number. Then all instances of this class will know the change.
If you really want to optionally change x in the __init__ method of an instance, you can still do it. Combining with #richflow's codes, it can look like the following.
class Myclass:
x = 0
def __init__(self, x=None):
if x is not None:
Myclass.x = x
# other codes for initializiing the instance
def check(self):
if Myclass.x == 2:
print("this is fine. going to print it")
def printing(self, z=0):
if z == 1 :
print("we got ", z)
else:
print(Myclass.x)
I tried not to change too much from your codes. Your main.py should work correctly with this class definition. However, the design looks a bit weird to me. Probably that's because I didn't understand clearly what the check and printing methods are really doing, and what the argument z is really doing in printing methods. If you provides more insights, probably people can help you with a better design.
This question already has answers here:
TypeError: Missing 1 required positional argument: 'self'
(8 answers)
Closed 2 years ago.
I know a similar question has been asked/answered several times. But please do read on ..
I am trying to create a Class from a string value as described in "Convert string to Python Class Object" in Python 3.6.
utils.py
class Foo(object):
def __init__(self):
print("In the constructor of Foo")
def What(self):
print("so what ... ")
class FooParam(object):
def __init__(self, v):
self.value = v
print("In the constructor of FooParam")
def What(self):
print("Value=" % self.value)
print("So what now ...")
welcome.py
def TEST1():
m = importlib.import_module("utils")
c = getattr(m, "Foo")
c.What()
if __name__ == '__main__':
TEST1()
Error
TypeError: What() missing 1 required positional argument: 'self'
So what am I doing wrong ?
Also how can I create an object of "FooParam" and pass a value to the constructor.
Once you import the module just access with the variable you stored imported module:
m = importlib.import_module("utils")
foo = m.Foo()
foo.What()
import_module performs the same steps as import.
This c = getattr(m, "Foo") line of code is equivalent f = Foo so that means you are not creating an instance instead you are getting a reference to that class.
I suspect that c is the class Foo but not an instance of the class.
This is equivalent to simply calling
Foo.what()
Which is why self is not defined!
Whereas what you want is to create an instance of the class (giving it a 'self' property), then call its method, i.e.
foo_instance = Foo()
foo_instance.What()
so try replacing c.What() with..
foo_instance = c()
foo_instance.What()
for FooParam:
#import the class FooParam
c = getattr(m, "FooParam")
#create an instance of the class, initializing its values (and self)
fooparam_instance = c(3.14)
#call its method!
fooparam_instance.What()
on the whole I would rename the variable c, to something like foo_import and fooparam_import respectively :)
I have a class where I pass a list of documents, and in a method, it creates a list of those documents:
class Copy(object):
def __init__(self, files_to_copy):
self.files_to_copy = files_to_copy
Here, it creates a list of files:
def create_list_of_files(self):
mylist = []
with open(self.files_to_copy) as stream:
for line in stream:
mylist.append(line.strip())
return mylist
Now, I try to access the method in another method in the class:
def copy_files(self):
t = create_list_of_files()
for i in t:
print i
Then I run the following under if __name__ == "__main__":
a = Copy()
a.copy_files()
This throws:
TypeError: create_list_of_files() takes exactly 1 argument (0 given)
Am I using the method wrong?
You need to call the method off self, which is the "1 argument" the method is looking for
t = self.create_list_of_files()
You need to call create_list_of_files as follow:
self.create_list_of_files()
You are not passing any variable to the class. In your init method, your code states that init takes one variable, files_to_copy. You need to pass the variable that stores the correct information. For instance:
class Copy(object):
def __init__(self, files_to_copy):
self.files_to_copy = files_to_copy
#need to pass something like this:
a = Copy(the_specific_variable)
#now, can access the methods in the class
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
In order to create a code, I have decided to create a python class to just define some variables with default value. you can see this as "struct" in C.
the file is name : ScreenStructure.py
Inside I have defined this code
class ViewIdleScreen():
def _init_(self):
self.menu_access = "id/no_id/21"
self.Call_app = "id/no_id/23"
self.Email_app = "idno_id/24"
self.Camera_app = "id/no_id/27"
self.Browser_app = "id/no_id/26"
self.Contacts_app = "id/no_id/9"
self.Calendar_app = "id/no_id/10"
self.Messaging_app = "id/no_id/11"
self.Notes_app = "id/no_id/12"
def Call_app(self):
return self.Call_app
In the main file, I have added :
from ScreenStructure import ViewIdleScreen
later in the code of the main file:
IdleScreenView = ViewIdleScreen()
print IdleScreenView.Call_app()
but instead of displaying "id/no_id/23" it display
<bound method ViewIdleScreen.Call_app of <ScreenStructure.ViewIdleScreen instance at 0x02A16990>>
First, you're naming __init__ _init_. This is wrong. You need two underscores.
Second, you're setting an attribute Call_app there, but that's the same name as the method you define later:
def Call_app(self):
return self.Call_app
In addition to being shadowed by the attribute (if __init__ were declared properly), this method returns the method itself, which is the bound method you're seeing.
Avoid the collision of attribute and method names, and name __init__ correctly
you should not make functions named the same as data members
hello = "hello world"
def hello():
print "goodbye!"
print hello
often times people will make a variable name preceded by an underscore or something
class X:
def __init__(self,*args):
self._x = "yellow"
def x(self):
return self._x
but as #mhlester points out a main problem is that you named __init__ incorrectly