This is my experimenting code:
def settingValues():
hi = "Hello"
name = "Jake"
isTrue = True
def callingValues():
print(hi, name, isTrue)
settingValues()
callingValues()
Obviously this emmits an error...
Is there an easy way to transfer the variables throughout the two functions?
What I will be using this for requires setting quite a lot of variables... so I cant use 'global' for all of them. :)
Just use OOP:
class SomeClass:
def __init__(self):
self.hi = "Hello"
self.name = "Jake"
self.isTrue = True
def callingValues(self):
print(self.hi, self.name, self.isTrue)
sc = SomeClass()
sc.callingValues()
The easiest way would be to define them as globals, which could then be accessed from all the functions in the same module
hi = ""
name = ""
isTrue = False
def settingValues():
hi = "Hello"
name = "Jake"
isTrue = True
def callingValues():
print(hi, name, isTrue)
settingValues()
callingValues()
Related
class Friend:
all = []
def __init__(self):
self.__fname = None
self.__lname = None
self.__fid = None
#property
def fname(self):
return self.__fname
#fname.setter
def fname(self, value):
self.__fname = value
#property
def lname(self):
return self.__lname
#lname.setter
def lname(self, value):
self.__lname = value
#property
def fid(self):
return self.__fid
#fid.setter
def fid(self, value):
self.__fid = value
#DB Class
class db_friend()
def db_load_friend(self, obj, fname,lname):
obj.fname = fname
obj.lname = lname
obj.fid = "XYZ"
obj.all.append(obj)
# function that acts on the friend class
def manage_friend():
fname = "Joe"
lname = "Root"
objfriend = Friend()
db_friend.db_load_friend(objfriend, fname,lname)
print (objfriend.fname) # this is not working
print (objfriend.fid) #this is not working
for user in objfriend.all:
print (objfriend.fid) #this is working
Both objfriend.fname and objfriend.fid is printing no value. I am trying to load the objfriend object by passing to the db_load_friend method of the db class. I am able to see the values if I loop through the "all" variable. May I know why this is not working or using the static variable "all" is the only way to do it?
You need to create an instance of db_friend so you can call the db_load_friend() method:
def manage_friend():
fname = "Joe"
lname = "Root"
objfriend = Friend()
objdbfriend = db_friend()
objdbfriend.db_load_friend(objfriend, fname,lname)
print (objfriend.fname)
print (objfriend.fid)
for user in objfriend.all:
print (objfriend.fid) #this is working
Or, since db_load_friend() doesn't need to use self, you could make it a static method.
class db_friend()
#staticmethod
def db_load_friend(obj, fname,lname):
obj.fname = fname
obj.lname = lname
obj.fid = "XYZ"
obj.all.append(obj)
I am trying to create a function, that if the user did not enter any value in input field then it sets the text value to 0 or to any other number.
value_text = [self.trig_side_a_value.text, self.trig_side_b_value.text, self.trig_side_c_value.text, self.trig_angle_A_value.text, self.trig_angle_B_value.text, self.trig_angle_C_value.text]
for i in value_text:
if i == "":
i = "0"
else:
pass
Thanks in advance!
OK, so there is quite a bit wrong here. I will try to answer this with as much explanation as possible.
One thing that is wrong:
value_text = [self.trig_side_a_value.text, self.trig_side_b_value.text, self.trig_side_c_value.text, self.trig_angle_A_value.text, self.trig_angle_B_value.text, self.trig_angle_C_value.text]
for i in value_text:
if i == "":
i = "0"
This creates a list value_text and populates it with copies of the text attributes. Changing what is in the list does not affect the elements of self..text.
What needs to happen is that you need to iterate through the attributes of the class, setting each attributes' text member:
Here is a solution:
class TextContainer():
""" This is a class with just one attribute 'text' """
def __init__(self, text=""):
self.text = text
class TestClass():
""" This class contains a set of TextContainer objects as its attributes. """
def __init__(self):
self.trig_side_a_value = TextContainer("a")
self.trig_side_b_value = TextContainer("b")
self.trig_side_c_value = TextContainer()
self.trig_angle_A_value = TextContainer("A")
self.trig_angle_B_value = TextContainer("B")
self.trig_angle_C_value = TextContainer()
def test_me(self):
""" Test the setting of each attribute """
for attr, container in self.__dict__.items():
if not container.text:
container.text = "0"
def __str__(self):
""" Returns a string representation of the class """
return "TestClass: ({}, {}, {}, {}, {}, {})".format(
self.trig_side_a_value.text,
self.trig_side_b_value.text,
self.trig_side_c_value.text,
self.trig_angle_A_value.text,
self.trig_angle_B_value.text,
self.trig_angle_C_value.text)
def main():
test = TestClass()
test.test_me()
print(test)
if __name__ == '__main__':
main()
Hope that helps. Others, please correct my usage of the __dict__ - I'm some shaky ground here.
im not sure what im missing but it says that my class variable (var1) is not defined
Class Example(var1):
if var1 ==1:
def func1(var2)
x = cursor.execute("SELECT * FROM examples WHERE Name = 'var2' ")
Return x
else pass:
Example(1).func1("example")
could be because im tired and its simple but im also kinda new to this. Any help would be great and thank you
The syntax Class Example(var1): means that you are creating a class, wich inherits from var1. If you want to define a function, use def Example(var1):
Your Syntax is very messed up, lost of mistakes, but cleaned up it would look like this:
class Example():
def __init__(self,var1):
if var1 ==1:
def func1(var2):
x = cursor.execute("SELECT * FROM examples WHERE Name = 'var2' ")
print(var2)
return x
else:
pass
#Example(1).func1("example") you can not call 'func1'. At this point it doesnt exists!!
example = Example(1)
Here is the modular way of achieving the result,
class Example():
def __init__(self, var):
self.var = var
def func(self):
if self.var == 1:
return cursor.execute("SELECT * FROM examples WHERE Name = 'var1' ")
elif self.var == 2:
return cursor.execute("SELECT * FROM examples WHERE Name = 'var2' ")
else:
pass
ex = Example(1)
# call func which automatically executes query based on value of var
ex.func()
I am attempting a practice task I found in an old programming book to increase my knowledge of classes in Python. The task is to create a program which allows a user to set up a series of tests for a school. Each test must contain no more than 10 questions. The task stated that the best way to do this was to use containment, and have the class 'Question' inside the class 'Test'
Basically, I should set up a class called Test which dewfines the basics of the whole test, and then a class called Quesion which sets up the question and passes it back to Test to be included in the array there. I'm having 2 major problems. Firstly, how do I get the setQuestion object in the Question class to pass data in to the Question array in the Test class. Secondly, how do I have the setQuestion object iterate the variable numberofQuestions since that's contained in the Test Class.
Here is the code. Not sure it's clear from the formatting but the Question class is inside the Test class:
class Test(object):
def __init__(self):
self.__testID = 0
self.__maxMarks = 0
self.__questions = []
self.__numberofQuestions = 0
self.__level = ""
self.__dateSet = ""
class Question(object):
def __init__(self):
self.__questionID = 0
self.__questionText = ""
self.__answer = ""
self.__marks = 0
self.__topic = ""
def setQuestion(self, questionID, questionText, answer, marks, topic):
self.__numberofQuestions = self.__numberofQuestions + 1
self.__questionID = self.__questionID
self.__questionText = self.__questionText
self.__answer = self.__answer
self.__marks = self.__marks
self.__topic = self.__topic
This is how I would do that:
class Test(object):
def __init__(self,id,marks):
self.__testID = id
self.__maxMarks = marks
self.__questions = []
self.__numberofQuestions = 0
self.__level = ""
self.__dateSet = ""
def setQuestion(self,question):
self.__numberofQuestions += 1
self.__questions.append(question)
class Question(object):
def __init__(self,id,text,answer,marks,topic):
self.__questionID = id
self.__questionText = text
self.__answer = answer
self.__marks = marks
self.__topic = topic
Now you can put question objects into the __question array of Test like that:
if __name__ == "__main__":
test = Test(1,100)
test.setQuestion(Question(1,"Text","Answer",50,"Topic"))
Please see the sample code:
a = [1,2,3,4,5] # main list
b = [4,5,6] #variable list nr1
c = [1,2] #variable list nr2
class union(object):
def __init__(self, name):
self.name = name
def common_numbers(self, variable_list):
self.variable_list = variable_list
for x in self.name:
if x in self.variable_list:
yield(x)
def odd_numbers(self, odds):
self.odds = odds
for x in self.variable_list:
if not x % 2 == 0:
yield x
''' I receive: builtins.AttributeError: 'union' object has no attribute 'variable_list'.'''
x = union(a)
print(list(x.odd_numbers(c)))
I am trying to understand how to call other function within same class. As you can see, I am trying to find odd numbers from common_numbers function.
Please understand this is sample work. I know there are plenty of solutions with or withouth using classes to get propriet result. But in this case, I don't need result, I would really appretiate if you could help me understand the calling other function within class. Sorry for my English and Thank you in advance.
You're getting the error because you never actually define self.variable_list. It's only defined once you call common_numbers(), but you never do that. You can define it when initiating:
class union(object):
def __init__(self, name, variable_list):
self.name = name
self.variable_list = variable_list
def common_numbers(self):
for x in self.name:
if x in self.variable_list:
yield(x)
x = union(a, b)
print list(x.odd_numbers(c))
or after initiating, but before calling odd_numbers:
class union(object):
def __init__(self, name):
self.name = name
def common_numbers(self):
for x in self.name:
if x in self.variable_list:
yield(x)
x = union(a)
x.variable_list = b
print list(x.odd_numbers(c))