function name is undefined in python class
Since test()
doesn't know who is abc
, that msg NameError: global name 'abc' is not defined
you see should happen when you invoke b.test()
(calling b.abc()
is fine), change it to:
class a:
def abc(self):
print "haha"
def test(self):
self.abc()
# abc()
b = a()
b.abc() # 'haha' is printed
b.test() # 'haha' is printed
Function name is not defined in a Python class
You forgot to add self
as the first argument of class' methods and when you use the methods. Corrected code:
class Logger:
@staticmethod
def get_timestamp():
import datetime
return datetime.datetime.utcnow()
def print_log(self, color, write_level, msg):
return color
def log_level_print(self, log_level, write_level, msg):
if log_level == 'ERROR':
return self.print_log(bcolors.FAIL, write_level, msg)
if log_level == 'WARN':
return self.print_log(bcolors.WARNING, write_level, msg)
if log_level == 'INFO':
return self.print_log(bcolors.OKGREEN, write_level, msg)
if log_level == 'DEBUG':
return self.print_log(bcolors.OKBLUE, write_level, msg)
else:
print(f"{Logger.get_timestamp()} {bcolors.FAIL}: Invalid LOG type{bcolors.ENDC}")
return
Look, it's a code I'm running:
demo = Logger()
print(demo.log_level_print('ERROR','ssdsd','sdsdsd'))
and this is a result:
name not defined' when setting a class to a variable
A few things.
Firstly, you're not "converting" your class into a variable. You're instantiating type and assigning that instance to a variable, something that holds a reference to an object.
Moving to the problem at hand. As the comments suggest and extending on that, you're fundamentally misunderstanding default parameters and instantiation.
In your first example you have period
and division
parameters which are both defined within the scope of the constructor (__init__
). It is valid to use these in the constructor because they exist in that scope.
Below this you attempt to instantiate Stuff
by passing variables called period
and division
which do not exist. They do not exist because you are outside of the scope of the constructor.
You need to create these
class Stuff():
def __init__(self, period = 1, division = 1):
print(str(period), str(division))
period = 1
division = 1
stuff = Stuff(period, division)
The defined variables have nothing to do with the parameters of the Stuff
class, other than the fact that they are passed in when instantiating this object.
In your second example you've removed these non-existent variables from the instantiation which is correct but you've also removed the default assignment of the parameters in the Stuff
class which is wrong. It's wrong because now you're instantiating an object whose constructor has required parameters, without this it does not know what to do with those parameters.
The error reflects this mandatory requirement
TypeError: __init__() missing 2 required positional arguments: 'period' and 'division'
For the second example, the correct syntax would be
class Stuff():
def __init__(self, period = 1, division = 1):
print(str(period), str(division))
stuff = Stuff()
python: function not defined
You need to use self
to call class methods, also your method check
didn't have a self
attribute.
class Solution(object):
a={1:'I',2:'II',3:'III',4:'IV',5:'V',6:'VI',7:'VII',8:'VIII',9:'IX'}
def check(self, num,s):
if num<=0:
return s
elif num<10:
return find(0,s+a[num])
elif num>=10 and num<50:
if num<=30:
return find(num%10,s+('X'*(num//10)))
else:
return find(num%10,s+'XL')
elif num>=50 and num<100:
if num<=80:
return find(num%10,s+('L'+'X'*(num//10)))
else:
return find(num%10,s+'XC')
elif num>=100 and num<500:
if num<=300:
return find(num%100,s+('C'*(num//100)))
else:
return find(num%100,s+'CD')
elif num>=500 and num<1000:
if num<=800:
return find(num%100,s+('D'+'C'*(num//100)))
else:
return find(num%100,s+'CM')
else:
return find(num%1000,s+'M'*(num//1000))
def intToRoman(self, num: int) -> str:
s = self.check(num,"")
return s
Related Topics
Pandas Fill Missing Values in Dataframe from Another Dataframe
Python Beautifulsoup Extract Text Between Element
Connecting to Microsoft SQL Server Using Python
Python - Rolling Functions for Groupby Object
Tkinter: Using Scrollbars on a Canvas
What Limitations Have Closures in Python Compared to Language X Closures
Pip - Fatal Error in Launcher: Unable to Create Process Using '"'
Importerror: No Module Named Crypto.Cipher
Python Read JSON File and Modify
How to Loop Through All But the Last Item of a List
Failed to Catch Syntax Error Python
Python Attributeerror: 'Module' Object Has No Attribute 'Serial'
Socket.Shutdown VS Socket.Close
What Is the Recommended Way of Allocating Memory for a Typed Memory View
Implement Matlab's Im2Col 'Sliding' in Python
E731 Do Not Assign a Lambda Expression, Use a Def
How to Solve Readtimeouterror: Httpsconnectionpool(Host='Pypi.Python.Org', Port=443) with Pip