why summ1 is not getting printed even it is defined in function? - python

class Student:
def __init__(self,m1,m2):
self.m1=m1
self.m2=m2
def add(self,s1,s2):
summ1 = self.m1 + self.m2
summ2 = s1.m1 + s1.m2
summ3 = s2.m1 + s2.m2
std1=Student(89,99)
std2=Student(95,99)
std3=Student(95,99)
std1.add(std2,std3)
print(summ1)
print(summ2)
print(summ3)
why summ1 is not getting printed even it is defined in function?
Well summ1,summ2,summ3 are defined in add function when I try to print them this code is giving me error.
Error is
NameError: name 'summ1' is not defined

summ1,summ2,summ3 are local variables defined in the function add and they are not visible outside of this function. If you replace them by self.summ1, self.summ2, self.summ3, then print(std1.summ1) etc. will work.

As AnkurSaxena said, you can not access your variables the way you try it.
The following code should solve your problem:
class Student:
def __init__(self,m1,m2):
self.m1=m1
self.m2=m2
self.summ1 = None
self.summ2 = None
self.summ3 = None
def add(self,s1,s2):
self.summ1 = self.m1 + self.m2
self.summ2 = s1.m1 + s1.m2
self.summ3 = s2.m1 + s2.m2
std1=Student(89,99)
std2=Student(95,99)
std3=Student(95,99)
std1.add(std2,std3)
print(std1.summ1)
print(std1.summ2)
print(std1.summ3)

Related

Problem using exec within class' function in Python

The following code works as expected
name = "Test"
myname = ""
exec('myname ="' + name + '"')
print(myname)
Which shows as result:
Test
Problem
However, if I define the same within a function in a class and execute it I get as result an empty string.
class new(object):
def __init__(self, name):
self.print(name)
def print(self, name):
myname = ""
exec('myname ="' + name + '"')
print(myname)
a = new("My name")
The above is a toy example code of a bigger code.
Question
How to define the function so as to get the same result? The exec function is actually needed in the bigger code.
You can pass a dictionary as the globals (or locals) for exec.
def print(self, name):
d = {"myname": ""}
exec('myname ="' + name + '"', d)
print(d["myname"])

Python NameError and I can not understand

I'm now practicing defining functions:
def get_seconds(hours, minutes, seconds):
return 3600*hours+60*minutes+seconds
Now, I want to exec the function:
amount_a = get_seconds(7200*minutes+30*seconds)
amount_b = get_seconds(__)
result = amount_a + amount_b
print(result)
Error:
NameError: name 'minutes' is not defined
First you define "get_seconds" function, you just need to do :
amount_a = get_seconds(hours=2, minutes=30, seconds=0)
amount_b = get_seconds(hours=0, minutes=45, seconds=15)

Getting a NameError for a variable I have defined in my Class

I am trying to run some code that allows me to either call the name Student or Programmer from the class I called Master_programmer. Here is the code I used.
class Master_programmer:
capabilities = []
student = "SoloLearn Student"
programmer = "Programmer"
def Student(self):
return 'SoloLearn Student'
def Programmer(self):
return 'Programmer'
def __init__(self, name):
self.name = name
def add_capabilities(self, capability):
self.capabilities.append(capability)
m1 = Master_programmer(programmer)
print(m1.Student, m1.Programmer)
a.add_capabilities('Stay Inspired')
b.add_capabilities('Find Clients')
b.capability
After running the above code, I get the following error
Traceback (most recent call last):
File "./Playground/file0.py", line 21, in <module>
m1 = Master_programmer(programmer)
NameError: name 'programmer' is not defined
Now, my question is, how do I get my code to deliver the expected results? e.g when I request for the Name 'programmer' to be called up, I expect it to bring up Programmer and then allow me to add capabilities to the programmer like "Find Clients". And for Student it must be "Stay Inspired".
I guess the below code and its comments will answer your question.
class Master_programmer:
STATIC_VARIABLE_ONE_FOR_EVERY_INSTANCES = 'This is Static Var'
def __init__(self, name):
self.name = name
self.capabilities = []
self.student = "SoloLearn Student"
self.programmer = "Programmer"
def get_student(self):
return self.student
def get_programmer(self):
return self.programmer
def add_capabilities(self, capability):
self.capabilities.append(capability)
# Create instance for your class and name it coder (or whatever you like)
coder = Master_programmer('Replace me with student name')
# to call coder object's variable
# you need to call it by object name just like below
print('capabilities: ', coder.capabilities)
print(coder.programmer)
print(coder.student)
coder.add_capabilities('Stay Inspired')
coder.add_capabilities('Find Clients')
print(coder.get_student())
print(coder.get_programmer())
print('capabilities: ', coder.capabilities)
print()
# you can invoke Static variables usign directly class name
# you can invoke usign instance name as well but, it is not convention
print(Master_programmer.STATIC_VARIABLE_ONE_FOR_EVERY_INSTANCES)
print()
# if you change Static member, it will get change for all of your instances
coder_2 = Master_programmer('Replace me with student name')
Master_programmer.STATIC_VARIABLE_ONE_FOR_EVERY_INSTANCES = 'changed'
print()
# print static var using both ways
print(Master_programmer.STATIC_VARIABLE_ONE_FOR_EVERY_INSTANCES)
print(coder.STATIC_VARIABLE_ONE_FOR_EVERY_INSTANCES)
print(coder_2.STATIC_VARIABLE_ONE_FOR_EVERY_INSTANCES)
m1 = Master_programmer(programmer)
print(m1.Student, m1.Programmer)
Is calling the variable programmer if you wan to refer to programmer = "Programmer" in the Master_programmer class you need to use Master_programmer.programmer instead.
Though your code will later crash if you don't initialse a and b too since you need to define them too like normal variables e.g. a = Master_programmer("EEZi") to call them and/ or work with them
Thank you all for your answers. Here is the final code that I went with and it works really well. Many Thanks to you.
class Master_programmer:
STATIC_VARIABLE_ONE_FOR_EVERY_INSTANCES = 'This is Static Var'
def __init__(self, name):
self.name = name
self.capabilities = []
self.student = "SoloLearn Student"
self.programmer = "Programmer"
def get_student(self):
return self.student
def get_programmer(self):
return self.programmer
def add_capabilities(self, capability):
self.capabilities.append(capability)
coder = Master_programmer('EEZi')
coder.add_capabilities('Stay Inspired!')
coder.add_capabilities('Find Clients')
a = coder.get_student()
b = coder.get_programmer()
capabilities = coder.capabilities
for i in range(0,1):
print(a)
print("Listen here, just", coder.capabilities[0], "\n")
print(b)
print("Hustle hard and", coder.capabilities[1])

Getting nameerror in python

I have the following function, I want to concat the 2 strings, What wrong am I doing here?
commands = ["abcd","123"]
def configure_dev(self, steps):
func_name = self.id + ':configure dev'
global conf_cmd
for key in commands:
conf_cmd += key + '\n'
print(conf_cmd)
Getting the following error:
conf_cmd += key + '\n'
After running it, I get this error:
NameError: name 'conf_cmd' is not defined
I added your code with your critical issue resolved.
commands = ["abcd","123"]
def configure_dev(self, steps):
func_name = self.id + ':configure dev'
global conf_cmd = '' // <-- ''
for key in commands:
conf_cmd+=key+'\n'
print(conf_cmd)
All you need to do is to add:
conf_cmd = ''
just after commands = ["abcd","123"]
Why?
global conf_cmd Does not create new string, it just means you can access the global variable.

NameError: name 'getTempo' is not defined

i'm getting an error defining function "getTempo" and i don't know why... Thanks for the help.
example:
L=[Musica("aerossol",4.9),Musica("lua",5.3),Musica("monte",3.2),Musica("rita",4.7)];getTempo("lua",L)
should give:
lua:5.3
5.3
class Musica:
def __init__(self,nome,tempo):
self.nome=nome
self.tempo=tempo
def __repr__(self):
return self.nome+":"+str(self.tempo)
def getTempo(nomeMusica,ListaMusicas):
if ListaMusicas==[]:
print ("Inexistente")
else:
meio=len(ListaMusicas)//2
print (ListaMusicas[meio])
A = [i[0] for i in ListaMusicas]
B = [i[1] for i in ListaMusicas]
if nomeMusica==A[meio]:
print (B[meio])
elif nomeMusica<A[meio]:
return getTempo(nomeMusica,ListaMusicas[:meio])
else:
return getTempo(nomeMusica,ListaMusicas[(meio+1):])
In python, unlike languages like Java or C++, instance attributes and methods must be accessed on the instance, so you must write self.getTempo in order for getTempo to resolve.
EDIT - Selective Reading Failure
You also need to make sure that all method definitions include an argument for the class instance itself, which will be the first argument passed. By convention, this is the self argument, but it can be any name you choose. Here is the modified function definition:
def getTempo(self, nomeMusica,ListaMusicas): # Changed
if ListaMusicas==[]:
print ("Inexistente")
else:
meio=len(ListaMusicas)//2
print (ListaMusicas[meio])
A = [i[0] for i in ListaMusicas]
B = [i[1] for i in ListaMusicas]
if nomeMusica==A[meio]:
print (B[meio])
elif nomeMusica<A[meio]:
return self.getTempo(nomeMusica,ListaMusicas[:meio]) # Changed
else:
return self.getTempo(nomeMusica,ListaMusicas[(meio+1):]) # Changed

Categories

Resources