python error NameError: name 'ofclass' is not defined - python

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()

Related

object method invokation is not possible

in the below code, i am trying to develop using the concept of multithreading and synchronization.
i developed the below code. however, at the run time, i receive the below error:
cls: <class '__main__.ThreadsWithSync'>
Traceback (most recent call last):
File "m:\python lessons\ThreadsWithSync.py", line 68, in <module>
t1.spawnThread
AttributeError: 'NoneType' object has no attribute 'spawnThread'
PS M:\python lessons>
please let me know why the method 'spawnThread' is not recognized
import threading
import logging
import time
from random import seed
from random import randint
class ThreadsWithSync():
def __new__(cls):
"""
For object creation
"""
print("cls: %s"%(cls))
cls.onCreateObject()
def __init__(self):
"""
For object initialization
"""
#print("self: %s"%(self))
self.onInitializeObject()
#classmethod
def onCreateObject(cls):
"""
This will be invoked once the creation procedure of the object begins.
"""
instance = super(ThreadsWithSync, cls).__new__(cls)
#print("instace: %s"%(instance.__repr__)) #activate this line whenever an informative and descriprtive text about the instance is needed to be displayed
return instance
def onInitializeObject(self):
"""
This will be invoked once the initialization procedure of the object begins.
"""
threading.Thread.__init__(self) #to initialize the super class
print("self: %s"%(self))
seed(1)
def __repr__(self):
"""
similar to toString in Java
"""
return "\n__class__: " + repr(self.__class__) +"\n__new__:" + repr(self.__new__) + "\n__str__: " + repr(self.__str__) + "\n__sizeof__: " + repr(self.__sizeof__)
def isNumPrime(self, targetNum):
if targetNum == 0 or targetNum == 1:
return False
isPrim = True
for i in range(targetNum):
if targetNum % i == 0:
isPrim = False
break
return isPrim
def spawnThread(self):
if __name__ == "__main__":
main()
def main():
while True:
thread_1 = threading.Thread(group = None, target = self.isNumPrime, name='Thread_1', args = (), kwargs=dict(targetNum=randint(0,100)), daemon = None)
thread_2 = threading.Thread(group = None, target = self.isNumPrime, name='Thread_2', args = (), kwargs=dict(targetNum=randint(0,100)), daemon = None)
t1 = ThreadsWithSync()
t1.spawnThread
You forgot to return the created object from __new__

python ray AttributeError : 'function' has no attribute 'remote'

I'm trying to use ray module to on an existing code based on if an env variable is true or not.
This is what I've done so far. this code structure is similar to mine but not exactly due to it's size.
import os
if os.getenv("PARALLEL"):
import ray
ray.init()
class A(object):
def __init__(self, attr):
self.attr = attr
def may_be_remote(func):
return ray.remote(func) if os.getenv("PARALLEL") else func
#may_be_remote
def do_work(self):
#work code
def execute(self, n):
for _ in range(n):
do_work.remote()
Then, I call the execute function of class A :
a = A()
a.execute(7)
I get AttributeError : 'function' has no attribute 'remote' on that line.
Where did I go wrong with this code please?
You are accessing remote() on the function do_work, which is not defined.
Did you mean to just call do_work()?
Unfortunately ray makes it hard to get transparent code to switch easily as you intend.
Following https://docs.ray.io/en/latest/ray-overview/index.html#parallelizing-python-classes-with-ray-actors the quite strange insert-.remote syntax is like...
import os
use_ray = os.getenv("PARALLEL") is not None
if use_ray:
import ray
ray.init()
def maybe_remote(cls):
return ray.remote(cls) if use_ray else cls
#maybe_remote
class A:
def __init__(self, attr):
self.attr = attr
def do_work(self, foo): # do something
self.attr += foo
def get_attr(self): # return value maybe from remote worker
return self.attr
if __name__ == '__main__':
n = 7
if use_ray:
a = A.remote(0)
for i in range(1, n + 1):
a.do_work.remote(i)
result = ray.get(a.get_attr.remote())
else:
a = A(0)
for i in range(1, n + 1):
a.do_work(i)
result = a.get_attr()
expect = int((n / 2) * (n + 1))
assert expect == result
Not sure there is also an easy (decorator) solution for the differences in the method calls.

NameError: name 'convert_symbol_to_int' is not defined

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?

Run process when variable is called

I wanted to run code placed inside of thing.process upon when I hit the command.processCommand object (when i'm looping through all of the commands placed inside of defined[]), is there a way I can achieve this? This aforementioned loop will be executed as is such in myproject.py
command.py
class Command:
global defined
defined = []
def __init__(self, name):
self.name = name
self.description = "This command lacks a description"
self.args = ""
self.process = None
defined.append(self)
eightball.py
def processCommand():
print('hello')
thing = commands.Command('8ball')
thing.description = "Gives you a response from the mighty 8ball."
thing.process = processCommand
myproject.py
# Cogs
import cogs.commands as commands
import cogs.eightball
import cogs.helloworld
def processCommands(message):
if(message.content[:2] == "b#"):
args = message.content.split(' ')
args[0] = args[0][2:]
for command in defined:
if args[0] == command.name:
command.args = args
command.processCommand
for x in defined:
if x.process: # to skip `self.process = None`
x.process()
EDIT: you need process() instead of processCommand
for command in defined:
if args[0] == command.name:
command.args = args
command.process()

Python : Object is not avaialbe on different file

I have created a singlton Here is the class description.
allsms.py
from DB.models import ApiKey,ServiceProvider
from DB.messagenet import MessageNet
class SMSMgr( object ):
_instance = None
_allsp = []
def __init__(self):
pass
def __new__(cls, *args, **kwargs):
if not cls._instance :
cls._instance = super(SMSMgr, cls).__new__(
cls, *args, **kwargs)
return cls._instance
def loadsettings(self):
get_all_sp = ServiceProvider.objects.filter(status = False)
for obj in get_all_sp:
cla = obj.class_Name
a=globals()[str(obj.class_Name)](obj.userName,obj.password,obj.sendingurl)
self._allsp.append(a)
#print self._allsp
def reload(self):
self._allsp = []
get_all_sp = ServiceProvider.objects.filter(status = False)
for obj in get_all_sp:
cla = obj.class_Name
a=globals()[str(obj.class_Name)](obj.userName,obj.password,obj.sendingurl)
self._allsp.append(a)
def send(self):
print "+++++++++++++++++++== Global send "
if __name__ == "__main__":
b = SMSMgr()
b.loadsettings()
Now in test.py file of the same directory I am trying to use the singleton object which stored in the _allsp variable like.
from SMShandler.allsms import SMSMgr
b = SMSMgr()
#b.loadsettings()
print b._allsp
This is printing empty list. But when I am doing like this:
b = SMSMgr()
b.loadsettings()
print b._allsp
it is printing the list of objects .
My question is, if the above design is singlton then why print b._allsp is printing empty list in test.py? I am already loading loadsettings in the allsms.py file .
You are running loadsettings() in an if __name__ == "__main__" block:
if __name__ == "__main__":
b = SMSMgr()
b.loadsettings()
The purpose of such a block is to happen only when the code is run directly (like python allsms.py). That means it won't happen when it is imported in the line:
from SMShandler.allsms import SMSMgr
If you put the line b.loadsettings() outside of the if block, you'll see that it will already be loaded.

Categories