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)?
Related
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 😁
I wonder if it is possible to set variables of a class by a different class using cls?
The story behind it:
I'm writing tests for different purposes but see that one part of the setup is the same as in an already existing class. So I would do the setUp by the already existing one:
The original code:
class TestBase(unittest.TestCase):
def setUp(self):
self.handler = txt.getHandler(hcu.handler3())
self.curves = self.handler.curves()
self.arguments = (getInit())
self.ac = self.connect2DB(self.arguments)
self.au = AutoUtils()
This has worked well so far.
Now in my TestClient I'd like to make use of that:
from .testsDB import TestBase as tb
class TestClient(unittest.TestCase):
def setUp(self):
tb.setUp()
And modified in the TestBase the setUp to the following:
#classmethod
def setUp(cls):
cls.handler = txt.getHandler(hcu.handler3())
cls.graph = cls.handler.curves()
cls.argv = (getInit())
cls.ac = cls.connect2DB(cls.arguments)
cls.au = AutoUtils()
But I'm getting an error as soon as I use one of the values defined in the variables of the TestClient-class:
def test_Duplicates(self):
self.testDB = self.ac.connect(self.ac.client, self.arguments[4])
With the error:
In test_Duplicate (Curves.tests_client.TestClient) :
Traceback (most recent call last):
File "/home/qohelet/Curves/tests_client.py", line 49, in test_Duplicate
self.testDB = self.ac.connect(self.ac.client, self.arguments[4])
AttributeError: 'TestClient' object has no attribute 'ac'
Is it actually possible what I'm trying?
EDIT:
After writing this and seeing the answers I did another review. Yes indeed there is a circular issue I'm having.
TestBase has the function connect2DB which will be executed on setUp.
If it refers to itself (as in the original) it's fine.
If I replace the self with cls it will try to execute TestClient.connect2DB in the setUp - which does not exist. So it would require self again as putting connect2DB into TestClient is not an option.
How to solve that?
Surely your new class should just inherit the setup()?
from .testsDB import TestBase as tb
class TestClient(tb):
def test_Duplicates(self):
self.testDB = self.ac.connect(self.ac.client, self.arguments[4])
The whole point of inheritance is that you don't modify what you inherit from. Your new class should just make use of what is supplied. That is why inheritance is sometimes called programming by difference.
class Member():
def __init__(self, MemberName, MemberID, SubcribtionPaid):
self.__MemberName = MemberName
self.__MemberID = MemberID
self.__SubcribtionPaid = False
def SetMemberName(self):
print(MemberName,self.__MemberName)
def SetMemberID (self):
print(MemberID,self.__MemberID)
def SetSubcriptionPaid(self):
print(SubcribtionPaid,self.__SubcribtionPaid)
class Jmember(Member):
def__init__(self,MemberName,MemberID,SubcribtionPaid,DateofJoining):
super().__init__(MemberName,MemberID,SubcribtionPaid)
self.__DateofJoining = DateofJoining
def SetDateofBirth(self):
print(DateofBirth,self.__DateofJoining)
NewMember = Jmember("Armeen","1245","True","12/3/2015")
NewMember.SetMemberName()
NewMember.SetMemberID()
NewMember.SetSubcriptionPaid()
NewMember.SetDateofJoining()
I basically copy pasted the code.I used pycharm. I still dont get how to use code block. I dont know what to do.
Sorry if i caused a problem.
I wrote a code in python,where one class inheritates the attributes of another class. When i run the code , error occurs on line 26 saying that super() takes atleast 1 argument .Even though i wrote the arguments. Did I make a mistake there. The code, the traceback
I want to see the output of the new member that includes member name, id , subcribtion paid and date of joining. But error is shown.
Updated my post to reflect your posted code:
You said that you are using PyCharm. pay attention to the red squiggly lines under sections as they are pointing out errors.
First error: you did not have a space between def and init
def__init__(self, MemberName, MemberID, SubcribtionPaid):
Second Error: found in your class function calls:
You do not have to call the class that is essentially what (self) is doing
def SetMemberName(self):
print(MemberName,self.__MemberName)
Third error: was found in your Traceback
You were trying to call a function that you forgot to create
Traceback (most recent call last):
File "/Users/sumbody/Projects/Python/MemberTest2/main.py", line 29, in <module>
NewMember.SetDateofJoining()
AttributeError: 'Jmember' object has no attribute 'SetDateofJoining'
Here is the working code:
class Member():
def __init__(self, MemberName, MemberID, SubcribtionPaid):
self.__MemberName = MemberName
self.__MemberID = MemberID
self.__SubcribtionPaid = False
def SetMemberName(self):
print(self.__MemberName)
def SetMemberID (self):
print(self.__MemberID)
def SetSubcriptionPaid(self):
print(self.__SubcribtionPaid)
class Jmember(Member):
def __init__(self,MemberName,MemberID,SubcribtionPaid,DateofJoining):
super().__init__(MemberName,MemberID,SubcribtionPaid)
self.__DateofJoining = DateofJoining
def SetDateofBirth(self):
print(self.__DateofJoining)
def SetDateofJoining(self):
print(self.__DateofJoining)
NewMember = Jmember("Armeen","1245","True","12/3/2015")
NewMember.SetMemberName()
NewMember.SetMemberID()
NewMember.SetSubcriptionPaid()
NewMember.SetDateofJoining()
Some advice, when learning to code and debug your own code, it is not a bad thing to take some code that runs and then break it. It sounds weird, but in doing so you will learn to recognize errors when seen in the editor and at runtime. Happy coding!
Given below is a snippet from a class of which I am trying to create objects and getting error:
class FoF(object):
def __init__(self,path):
filepath=[]
filepath.append(self.FileOrFolder(path))
Upon executing which I get the following error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "PathOps.py", line 6, in __init__
def __init__(self,path):
NameError: global name 'filepath' is not defined
After which I tried:
filepath=[]
class FoF(object):
def __init__(self,path):
global filepath.append(self.FileOrFolder(path))
And again:
File "<stdin>", line 1, in <module>
File "PathOps.py", line 6, in __init__
global filepath.append(self.FileOrFolder(path))
NameError: global name 'filepath' is not defined
What is causing the error and how do I fix it?
Try using insted of global the special word self.
So something like this
class FoF(object):
def __init__(self,path):
self.filepath=[]
self.filepath.append(self.FileOrFolder(path))
The reason this error comes up is because what python thinks you're trying to do is one of two things:
Either you're trying to reference a global variable called filepath -- which is clear that's not what you're trying
What's not so clear is that you could also define a class attribute called filepath -- the only problem with that is that you can't define a class attribute with a function of that class. You can only do so within the class -- outside a class function
So in order to declare variables within a function you have to use the word self before it.
Edit** if you want it to be an attribute of the class -- as I'm assuming is what you meant you could do so like this:
class FoF(object):
filepath=[]
def __init__(self,path):
self.filepath.append(self.FileOrFolder(path))
I don't think you're giving us enough information. For example:
>>> class FoF(object):
... def __init__(self, path):
... junk = []
... junk.append(path)
...
>>> foo = FoF('bar/path')
produces no error.
What, exactly, are you trying to do?
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)