Python import class from local folder - python

I have 2 classes. The first is named test and goes as following:
import textbox
class test:
a=textbox("test")
a.run()
the second class is textbox and goes as following:
class textbox():
def __init__(self, string):
self.string=string
def run(self):
print string
i get this error
File "C:\Users\User\Desktop\edoras\gui\test.py", line 4, in test
a=textbox("test")
TypeError: 'module' object is not callable
I use the pydev eclipse plugin

Try
a = textbox.textbox("test")
or alternatively use
from textbox import textbox

Not sure about the error you mention, but your print statement in text box.run is wrong:
print self.string

You are calling directly the module textbox, which is not allowed.
Maybe it contains an omonymous function? In that case you should call
textbox.textbox('test')
(the first textbox would be the module name, and the second a function inside it)

Related

fix the error of File " line 1, in <module> NameError: name 'Account' is not defined

I run those code in Python online, but get the error message 'File "", line 1, in
NameError: name 'Account' is not defined'; I wonder how I could define "Account" there? thanks a lot! This is my first Python code.
class SavingAccount(Account):
def _init_(self, holder_name, saving_rateaccount_number=None):
super()._init_(holder_name, account_number)
self.saving_rate = saving_rate
def _repr_(self):
return 'SavingAccount('+str(self.holder_name)+', '+str(self.saving_rate)+', '+str(self.account_number)+')'
saving_account=SavingAccount('saving_1', 0.02)
print(saving_account)
If you define the class Account in another Python file, you have to have from other_file import Account before class SavingAccount(Account): to make it work.
When you do:
class My_class ( Other_class ):
def __init__(self,...):
# code lines
def my_method(self,...):
# more code
It means that My_class object will inherit Other_class methods and atributes, so you will have to define Other_class before in order to use it in My_class. In conclusion the new class will have it's own methods and atributes and also Other_class methods and atributes.
Example:
class Other_class():
def __init__(self,...):
# constructor code lines
def other_method(self,...):
# more code lines
class My_class( Other_class ):
def __init__(self,...):
# other constructor code lines
def my_method(self,...):
# some more code lines
You can find the full information in Python documentation.
PS: my recomendation is to always see the official documentation, you can even discover more thinks and expand you knowledge on the language. By the way you will see how useful is Python, keep it up 😁

How to access the object returned by a function inside python class

I have the following python class:
class Example(QMainWindow):
def onChanged(self, text):
return text
def buttonClicked(self):
print(self.onChanged)
when I run the script i get the following result:
<bound method Example.onChanged of <__main__.Example object at 0x7fde1cab0550>>
My question is how to get the content of the text returned in onChanged function ?
Thank you.
When you execute print(self.onChanged) you don't call the function, you should execute print(self.onChanged()) instead.

Class Solution - NameError: name 'Solution' is not defined

I tried all possible things to resolve this on compilation but still get this message. Is there anything wrong with class and function definition ?
class Solution:
def longestPalindrome(self, s):
s = 'tracecars'
print(str(Solution().longestPalindrome(s)))
PyCharm 2019.1.3 with Python 3.8
File "C:/Nityam/PythonProjects/DailyProblems/Palindrome.py", line 1,
in
class Solution:
File "C:/Nityam/PythonProjects/DailyProblems/Palindrome.py", line 7,
in Solution
print(str(Solution().longestPalindrome(s))) NameError: name 'Solution' is not defined
Process finished with exit code 1
First of all we can't reproduce your error.
Second one - your class method doesn't return anything.
Third - you don't create class object (it's OK - you can create it inline as you did, but why then do you need a class?)
Maybe you want something like this:
class Solution:
def longestPalindrome(self, s):
s = 'tracecars'
# some code here
return s
solution_obj = Solution()
print(str(solution_obj.longestPalindrome('somestring')))
also read about __init__ method for class - maybe you want s be a inner class variable (field)?

How can I move a nested class to a separate file

In my Python class I have a nested class defined and it works well, but when I try to move the nested class to a separate file I'm having trouble importing it.
I've tried to follow a few tutorials on Mixins and importing but I keep running into the issue of my object not having the attribute of the new method.
class SomeClass():
def __init__(self):
pass
# # This works
# class NestedClass():
# def helloWorld():
# print("Hello World")
# But when I move it to a separate file (nestedclass.py) I'm having trouble importing
from nestedclass import NestedClass
c = SomeClass()
c.NestedClass.helloWorld() # throws an error when I try to import
The error message I receive is "Attribute Error: 'NestedClass' object has no attribute 'helloWorld'

user defined class serialization and deserialization in python

I am very new to python : I want to serialize and deserialize my custom object in python. Please guide me on the same. I have a sample class :
import pickle
import json
class MyClass():
variable = "blah"
num = 10
def function(self):
print("this is a message inside the class.")
def get_variable():
return variable
def get_num():
return num
def main():
myObj = MyClass()
with open('/opt/infi/deeMyObj.txt', 'w') as output:
pickle.dump(myObj, output,pickle.HIGHEST_PROTOCOL)
with open('/opt/infi/deeMyObj.txt', 'r') as input:
myObjread = pickle.load(input)
print myObjread.get_variable()
print myObjread.get_num()
main()
I am getting following error :
Traceback (most recent call last):
File "sample.py", line 30, in
main()
File "sample.py", line 27, in main
print myObjread.get_variable()
TypeError: get_variable() takes no arguments (1 given)
Main intention is to read the object back.
To expand on jasonharper's comment, your get_variable and get_num methods aren't referring to the class's member variables. They should take the object as their first argument, e.g.
class MyClass:
...
def get_variable(self):
return self.variable
I think your serialization code is OK, but I might be wrong.
(Aside)
This is a bit off-topic, but another thing to note: when you define variables directly within the class block, they're defined on the class, not on objects of that class. That happens to work out in this case, since Python will look for a class-level variable of the same name if it can't find one on the object. However, if you store, say, a list in one of them and start modifying it, you'd end up sharing it between objects, which is probably not what you want. Instead you want to define them on in an __init__ method:
class MyClass:
def __init__(self):
self.variable = "blah"

Categories