Import class in same file in Python [closed] - python

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm new to python and I have a file with several classes. In a method in the class "class1" I want to use a method from another class "class2". How do I do the import and how do I call the method from class1? I have tried several different things but nothing seems to work.

You don't need to import them, because they are already in the same file.
Instead, do something like this:
class1 = Class1() #assigns class1 to your first class
Then call a method inside of Class1 like this:
Class2():
def method2(self):
class1.method1() #call your method from class2
Basically you are taking Class2() and pointing it to the instance class2, then you are calling a method of that class by doing class2.method2(). It's just like calling a function from the current class, but you use instance name in front of it.
Here is an example:
class Class1():
def method1(self):
print "hello"
class Class2():
def method2(self)
class1 = Class1()
class1.method1()
Then, when you call Class2() it will print 'hello'.

Let's say your file with all the classes is called myclass.py with the following:
class Class2(object):
def foo(self):
return 'cabbage'
class Class1(Class2):
def bar(self):
return self.foo()
In your main script, you can import the module as usual:
import myclass
And now you can create an instance of class1:
myinstance = myclass.Class1()
Then you can call the function directly:
myinstance.bar()
# Returns 'cabbage'

If all of the classes are in the same file, you don't need to import them. They are in the module scope already. Here's an example:
class A():
def print_one(self):
print "one"
class B():
def print_two_and_one(self):
print "two"
A().print_one()
B().print_two_and_one()

Related

Using self and parameters in a Python Script [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I'd like to use self (for global variables) and the parameters from the command-line in my Python Script but can't really get them to work.
def otherFunction(self)
print self.tecE
def main(argv,self):
self.tecE = 'test'
otherFunction()
if __name__ == "__main__":
main(sys.argv[1:],self)
This gives me an error:
main(sys.argv[1:],self)
NameError: name 'self' is not defined
So how and where to define self?
Usually the python convention of self is to be used in python classes, you did a bit of a mess.
So either you are not using classes and treating self just as a global dict, like this:
import sys
myglobal = {} # Didn't want to name it self, for avoiding confusing you :)
def otherFunction():
print myglobal["tecE"]
def main(argv):
myglobal["tecE"] = 'test'
otherFunction()
if __name__ == "__main__":
main(sys.argv[1:])
Or writing a class, like this:
import sys
class MyClass():
def otherFunction(self):
print self.tecE
def main(self, argv):
self.tecE = 'test'
self.otherFunction() # Calling other class members (using the self object which actually acting like the "this" keyword in other languages like in Java and similars)
if __name__ == "__main__":
myObj = MyClass() # Instantiating an object out of your class
myObj.main(sys.argv[1:])
So how and where to define self?
You will use self:
As the first argument of your class methods def my_method(self, arg1, arg2):
Within the class to refer to any other class members (just as demonstrated above) self.do_job("something", 123)
For creating class members: self.new_field = 56 Usually in __init__() constructor method
Note: decalring a class variable without the self.new_var, will create a static class variable.

python - calling variable from another function [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
iam working on tkinter iam using filedialog to upload file my target is to have tow button.
button1 for uploading txt file
button2 is for processing the file see my current function setup
class procFile:
def uploadFile(self, filename):
self.filename = filename
def displayName(self):
return self.filename
def filePath(self):
print("%s" %self.filename)
def main():
upload = procFile()
upload.uploadFile(filedialog.askopenfilename(filetypes=(('txt', '*.txt'), ('All Files', '*.*'))))
upload.filePath()
Please i need to another button to fireup another function which will access the variable from main function
Although your question is dull in providing detail, here are two ways that results to what I understood of your question.
Method 1
If you want to access the class variable in a function outside the class then:
class Class:
# do something
# example:
def __init__(self):
self.var = 2
print(self.var)
def outsideFunc():
# operations you want to do
# example:
print(a.var * 3)
Result
>> a = Class()
2
>> outsideFunc()
6
Note that outsideFunc() can be defined anytime during the program. However, you can only call outsideFunc() after the class has been initialized.
The reason for this is because filepath is an instance of the class procfile which is only defined once the class is initialized. The period after the initialized class can be followed by various objects such as a function Class.func(), a variable Class.var or even a nested class Class.subClass
Method 2
If you want to access the class variable inside the class then:
class Class:
# do something
# example:
def __init__(self):
self.var = 4
print(self.var)
def func(self):
# operations you want to do
# example
print(self.var + 5)
Result
>> b = Class()
4
>> b.func()
9
Just do the same what you have done before which is accessing the variable through self.var in the class.
Compare
Method 1 requires that when you call the class variable in an outside function, it has to be the same as the variable name you used to initialize the class. So when you do a = Class(), any function outside the class that refers to the initialized class will have to do a.object where object can be function, variable, or subclass.
Method 2 requires the same thing. However, when the function inside the class is referring to one of it's variables, then it needs to use self.object where object can be function, variable, or subclass.
Both require that you initiate the class first with varName = className() in which varName is just a variable used to reference the class. Afterwards, you do as before with varName.object

Class object is not defined [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'm trying to reference class object inside another class. In the sample code below, I want to be able to call Class1 methods from Class3, but they must be created in order where Class1(ClassObject) creates Class2 and Class2 creates Class3. Class3 must be then able to call ClassObject.
Code below gives not defined error.
NameError: global name 'ClassObject' is not defined
Any workarounds or fixes to this problem?
class Class1:
def __init__(self):
Class2()
def method(self):
print("test")
class Class2:
def __init__(self):
Class3()
class Class3:
def __init__(self):
ClassObject.method()
ClassObject = Class1()
Assignment are executed right to the left. It means that Class1() is computed before ClassObject is defined.
Before the affectation, the global scope looks like ['Class1', 'Class2', 'Class3'].
So the following stack happens:
"Class1()" is called -> get Class1 reference in the global scope
Class1.__init__
-> "Class2()" is called -> get Class2 reference in the global scope
-> Class2.__init__
-> "Class3()" is called -> ... you might know now.
-> Class3.__init__
-> ClassObject.method()
-> try to get ClassObject from global scope
-> raises exception: ClassObject isn't defined
Inde
I would like to give you a valid code, but your 3 classes haven't any meanings...
When Class1() is called there is no ClassObject global variable.
Since in python there are no variable declarations, the variable can be accessed only when it is defined, which means when it has a value. In your case the value would the that instance, but that instance is trying to reference the global variable before the assignment is complete.
If you want to reference the object in the assignment you must use self. However, in your code Class3 doesn't have any access to the Class1 instance so you'll get a different error.

calling a function in python got nothing instead [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I got a code like this.
....
class SocketWatcher(Thread):
....
def run(self):
....
TicketCounter.increment() # I try to get this function
...
....
class TicketCounter(Thread):
....
def increment(self):
...
when I run the program I got this error.
TypeError: unbound method increment() must be called with TicketCounter instance as first argument (got nothing instead)
i there any way that I can call the increment() function from TicketCounter Class to the SocketWatcher Class? or Does my calling is wrong...
You must create an instance of the class TicketCounter first before you can call any functions from it:
class SocketWatcher(Thread):
....
def run(self):
....
myinstance = TicketCounter()
myinstance.increment()
Otherwise the method is not bound anywhere. Creating an instance binds the method to the instance.
Member functions are part of the instances of a Class. So whenever you want to call you must always call it with an instance of the Class and not the Class name itself.
You could do:
TicketCounter().increment()
What this does is that it initialises an object and then calls this function. The following example will make it clear.
class Ticket:
def __init__(self):
print 'Object has been initialised'
def counter(self):
print "The function counter has been invoked"
And the output to illustrate this:
>>> Ticket().counter()
Object has been initialised
The function counter has been invoked
>>>
You are passing self, so I'm assuming that you need to create an instance. But if the method really doesn't need an instance then you can use the #classmethod or #staticmethod decorators and your code would work:
class TicketCounter(Thread):
#classmethod
def increment(cls):
...
or
class TicketCounter(Thread):
#staticmethod
def increment():
...
both can be called as TicketCounter.increment()

how to return a function in a different class in python 3.3 [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I know this is a really bad description but how can i get this to work:
class Test1():
def test_p1():
print("This is part 1 of Test1")
def Test2():
return test_p1()
Thanks in advance!
Well, there are several options.
The most basic are:
Create instance first
class Test1():
def test_p1(self):
print("This is part 1 of Test1")
def Test2():
return Test1().test_p1()
However, you should use it when having new instance makes sense (depends on your API).
Make it class method
class Test1():
#classmethod
def test_p1(cls):
print("This is part 1 of Test1")
def Test2():
return Test1.test_p1()
Make it static method (discouraged)
class Test1():
#staticmethod
def test_p1():
print("This is part 1 of Test1")
def Test2():
return Test1.test_p1()
Alternative: use inheritance
In some cases (maybe it is your case too, we do not know) it makes sense to actually utilize inheritance: create a class that will inherit from Test1. This way you can override parts of it and refer to parent methods. Example:
class Test1():
def test_p1(self):
print("This is part 1 of Test1")
class SomeOtherClass(Test1):
def test2(self):
return super(SomeOtherClass, self).test_p1()
and then use it like this:
my_instance = SomeOtherClass()
result = my_instance.test2()
But again, it really depends on your API / library.
Alternative 2: module-level function
User #user2357112 correctly pointed out, that module-level function can be even better (simpler) idea:
def test_p1():
print("This is part 1 of Test1")
def Test2():
return test_p1()
Side note: PEP8
To avoid confusion, as Python is really dynamic, you should give a "hint" to developers on what they are using, and in general follow coding style defined in PEP8:
module names are all_lower_case,
functions and methods are also all_lower_case,
classes are CamelCase (same applies to factory-like functions returning class instances),
constants are ALL_UPPER_CASE,
object properies are all_lower_case,
(and many more - the above is only about non-confusing naming)
Tadeck gave a detailed answer while I was typing mine, but here is my initial solution to what I believe you are trying to accomplish. I'm adding my input simply because I'm new to Python and I think a beginner's perspective may be beneficial for OP.
class Test1():
def test_p1(self):
print "This is part 1 of Test1"
def Test2():
myTest = Test1()
return myTest.test_p1()
Test2()
In your original code you attempt to call the test_p1 method without ever instantiating the Test1 class. So I did that first, myTest = Test1(), and then called the test_p1() method using my newly created myTest object.
Also, I added self to the argument list in the test_p1 method. I don't exactly understand why but apparently the lack of self makes it an unbound method which causes some problems.
You have to specify the class containing the functin. Call Test1.test_p1().
(Works in python3, but not in 2.x as there is this fuzz about bound and unbound thingies.)
Maybe you would want to use capital letters for classes and minuscules for functions.
A more common case is the following:
You have a class that defines methods:
class Animal:
def bark (self): print ('woof')
Then somewhere else you instantiate an object of this class and then invoke the method of the instance:
spike = Animal ()
spike.bark ()

Categories

Resources