NameError: name 'convert_symbol_to_int' is not defined - python

I've got an error: NameError: name 'convert_symbol_to_int' is not defined when I run this code:
class ReadData():
def __init__(self, sheet_path):
self.book = xlrd.open_workbook(sheet_path)
self.sheet = self.book.sheet_by_index(1)
self.users = []
def read(self):
for row_index in range(2, self.sheet.nrows):
rows = self.sheet.row_values(row_index)
if rows[1] != '' and rows[2] != '' and rows[4] != '':
woman = convert_symbol_to_int(row[8])
man = convert_symbol_to_int(row[9])
def convert_symbol_to_int(self,arg):
if arg == '○':
return 2
elif arg == '×':
return 1
elif arg == '△':
return 0
else:
return -1
x = ReadData('./data/excel1.xlsx')
x.read()
I really cannot understand why this error happens.
Why can't I access convert_symbol_to_int? How should I fix this?

you should use
man = self.convert_symbol_to_int(row[9])

Exactly as Kalyan Reddy already answered, you have to call the method with self, which is a pointer to the class itself. The following example shows the difference between externally declared functions and methods defined within the class:
def hello():
print("hello, world!")
class Greeting(object):
def __init__(self, world):
self.world = world
def hello(self):
print("hello, {}!".format(self.world))
def make_greeting(self):
hello() # this will call the function we created outside the class
self.hello() # this will call the method defined in the class
The purpose of self has already been explained in this question:
What is the purpose of self?

Related

How can I mock an attribute of a class using the mock decorator?

#these classes live inside exchanges/impl/tse/mixins.py
class PacketContext:
capture_tstamp = None
def __init__(self, capture_tstamp=None):
self.capture_tstamp = capture_tstamp
class SubParserMixin():
def __init__(self):
self.context = PacketContext()
def on_packet(self, packet):
self.context.capture_tstamp = packet.capture_timestamp
self.parse_er_data(packet.payload)
#this mock test lives in another python file
from exchanges.impl.tse.mixins import PacketContext
#patch.object(PacketContext, 'capture_tstamp', 1655417400314635000)
def test_receive_timestamp(self):
"""
test receive_timestamp is passed down correctly from PacketContext to on_packet()
"""
assert self.context.capture_tstamp == 1655417400314635000
I am trying to mock the self.capture_tstamp attribute in the PacketContext() class.
But in the above, I am getting an error that says
AssertionError: assert None == 1655417400314635000
E + where None = <exchanges.impl.tse.mixins.PacketContext object at 0x7fb324ac04c0>.capture_tstamp
E + where <exchanges.impl.tse.mixins.PacketContext object at 0x7fb324ac04c0> = <tests.unit.exchanges.tse.test_quote_write.TestTSE testMethod=test_receive_timestamp>.context
It seems very strange that the program is not recognising PacketContext().
You can make use of the patch.object decorator as below
class PacketContext:
capture_tstamp = None
def __init__(self, capture_tstamp=None):
self.capture_tstamp = capture_tstamp
<import_PacketContext_here>
#patch.object(PacketContext, 'capture_tstamp', 1655417400314635000)
def test_receive_timestamp():
test_instance = PacketContext()
assert test_instance.capture_tstamp == 1655417400314635000

How to pass a variable from a function to a class?

How can I print path outside function:
class FirstClas:
path = ''
def num(self):
path = "C:\\Users\\JOHN\\Desktop\\test.txt"
return path
print(path)
This method don't print anything.
This result:
C:\Python\python.exe C:/Users/JOHN/Desktop/test/tt.py
Process finished with exit code 0
You need to create an instance from the class that you created.
I would suggest doing this:
test = FirstClas()
print(test.num())
Hope this helps
Your method never gets called, and the class variable path is pointless here. Do:
class FirstClas:
def num(self):
path = "C:\\Users\\JOHN\\Desktop\\test.txt"
return path
print(FirstClas().num()) # note that this is outside the class!
I don't think you quite understand the purpose of classes, but here's how to make what you have "work" (in the sense that there are no fatal errors):
File global_variable.py
def init_global_variable():
"""initialize variable"""
global GLOBALS_DICT
GLOBALS_DICT = {}
def set_variable(name, value):
"""set variable"""
try:
GLOBALS_DICT[name] = value
return True
except KeyError:
return False
def get_variable(name):
"""get variable"""
try:
return GLOBALS_DICT[name]
except KeyError:
return "Not Found"
init_global_variable() # ADDED.
File tt.py
import os
#import lib.global_variable as glv
import global_variable as glv # Since I don't have your whole package.
class FirstClas:
def num(self):
path = "C:\\Users\\JOHN\\Desktop\\test.txt"
return path
def imag(self):
icon_file = os.path.join(
glv.get_variable("APP_PATH"),
glv.get_variable("DATA_DIR"),
"paths",
"PathExcel",
)
return icon_file
class Second:
# Put statements in a method so they don't run when the class is defined.
def run(self):
test = FirstClas()
print('first: ' + test.num())
print('second: ' + test.imag())
second = Second()
second.run()
Output:
first: C:\Users\JOHN\Desktop\test.txt
second: Not Found\Not Found\paths\PathExcel
the path does not changed(path = ' ') because you don't run the function num

How can i access a variable from one function to another?

def move(self):
z = self.comboBox.currentText()
print(z)
Hospital = newtest.my_function()
i = Hospital.index(z)
print('The index of :', i)
user = newuser.my_function()
global (user[i])
print (user[i])
return user[i]
def my_doc():
url = 'https://test.com/steth/get-list'
myobj = {'mongoId': 'user[i]'}
x = requests.post(url, data = myobj)
y=x.json();
print(y)
my_doc()
I need to get user[i] in the second function my_doc.so i made user[i] global.But it is showing syntax error as
global (user[i])
^
SyntaxError: invalid syn
Just get the return of one function, and input it into the other.
class Obj:
def func1(self):
return "something"
# Assuming func2 is inside class.
def func2_class(self, something):
print(something)
# Assuming func2 is outside class.
def func2(something):
print(something)
obj = Obj()
something = obj.func1()
func2(something) # Outside class.
obj.func2(something) # Inside class.

python error NameError: name 'ofclass' is not defined

I have an task to do to figure out what the code below does. it looks like it was constructed in python2 but I want to use python3. I have installed argparse which it requires and set up necessary file path but every time I run the program in command Line I get these issues.
Traceback (most recent call last):
File "C:\Users\Name\pythonScripts\Noddy.py", line 6, in <module>
class Noddy:
File "C:\Users\Name\pythonScripts\Noddy.py", line 63, in Noddy
if __name__ == '__main__': main()
File "C:\Users\Name\pythonScripts\Noddy.py", line 57, in main
ent = Noddy.make(fools)
NameError: name 'Noddy' is not defined
The code is below.
#! python3
class Noddy:
def __init__(self, x):
self.ant = None
self.dec = None
self.holder = x
#classmethod
def make(self, l):
ent = Noddy(l.pop(0))
for x in l:
ent.scrobble(x)
return ent
def scrobble(self, x):
if self.holder > x:
if self.ant is None:
self.ant = Noddy(x)
else:
self.ant.scrobble(x)
else:
if self.dec is None:
self.dec = Noddy(x)
else:
self.dec.scrobble(x)
def bubble(self):
if self.ant:
for x in self.ant.bubble():
yield x
yield self.holder
if self.dec:
for x in self.dec.bubble():
yield x
def bobble(self):
yield self.holder
if self.ant:
for x in self.ant.bobble():
yield x
if self.dec:
for x in self.dec.bobble():
yield x
def main():
import argparse
ap = argparse.ArgumentParser()
ap.add_argument("foo")
args = ap.parse_args()
foo = open(args.foo)
fools = [int(bar) for bar in foo]
ent = Noddy.make(fools)
print(list(ent.bubble()))
print
print(list(ent.bobble()))
if __name__ == '__main__': main()
Your def main() and if __name__=='__main__' have been written inside your class. The interpreter tries to execute them while it is defining the class, and can't, because the class Noddy doesn't exist until the class definition is finished.
Fix the indentation so that the main stuff lies outside your class.
class Noddy:
def __init__(self, x):
self.ant = None
self.dec = None
self.holder = x
# other methods INSIDE the class
# ...
# Notice the indentation — this function is OUTSIDE the class
def main():
# whatever main is supposed to do
# ...
if __name__=='__main__':
main()

output is not printing string in python

i have made a program but the output that i'm getting is
(<q3v3.Student instance at 0x023BB620>, 'is doing the following modules:', ' <q3v3.Module instance at 0x023BB670> <q3v3.Module instance at 0x023BB698>')
For example , the above output should give me Alice is doing following module : biology, chemistry
Help
this is my full code:
class Student :
def __init__(self,students):
self.students= students
print self.students
#def __str__(self): # when i used this i've got error type TypeError: __str__ returned non-string (type NoneType)
#print str(self.students)
class Module:
def __init__(self,modules):
self.modules = modules
print self.modules
#def __str__(self):
#print str(self.modules)
class Registrations (Student,Module):
def __init__(self):
self.list= []
self.stulist = []
self.modulist= []
def __iter__(self):
return iter(self.list)
def __str__(self):
return str(self.list)
def add(self,students,modules):
self.list.append((students,modules))
#print (self.list)
def students(self,modules):
for i in self.list:
if i[1] == modules:
self.modulist.append((i[0]))
return iter(self.modulist)
def __str__(self):
return str(self.students)
def modules(self,students):
for i in self.list:
if i[0] == students:
self.stulist.append((i[1]))
return iter(self.stulist)
def __str__(self):
return str(self.modules)
i need to import my program to be able to run it to this :
from q3v4 import *
james = Student('james')
alice = Student('alice')
mary = Student('mary')
agm = Module('agm')
ipp = Module('ipp')
r = Registrations()
r.add(james,agm)
r.add(alice,agm)
r.add(alice,ipp)
mstr = ''
for m in map(str,r.modules(alice)):
mstr = mstr+' '+m
print(alice, 'is doing the following modules:', mstr)
sstr = ''
for s in map(str,r.students(agm)):
sstr = sstr+' '+s
print(agm, 'has the following students:', sstr)
print(r)
You could define a __str__ method in your Student class, and do something like this:
def __str__(self):
return self.name # Here the string you want to print
Are you using Python 2? If so, print is a keyword, not a function. There are two ways to solve your problem:
Write print foo, bar instead of print(foo, bar).
The difference is that print(foo, bar) is actually printing out the tuple (foo, bar), which uses the repr() representation of each element, rather than its str().
At the very top of your file, write from __future__ import print_function. This will magically convert print from a keyword into a function, causing your code to work as expected.
If you are using Python 3, my answer is irrelevant.

Categories