I am trying to learn python. I am making a small program that holds some number or string on a static array. I want my function to hold variables in a single array. But after I finished my function, the array is also gone. How can I make my array static in python? I want to change it in several functions.
py_ppl = []
def Dong():
alc1 = alc.get()
alc2 = alc1
alc1 = [0]
py_ppl.append(alc1[0])
py_ppl.append(alc2)
I mean something like this. I get alc with Tkinter Gui.
This example of using class variables may help you. Variables declared in init are local to each instance of the class and variables declared at the top of the class are global to all instances of the class.
class funkBox:
globalToBox = [] # our class variable
def __init__(self):
pass # our do nothing constructor
def funk(self,elm): # our function
self.globalToBox.append(elm)
def show(self): # for demonstration
print(self.globalToBox)
a = funkBox() #create one instance of your function holder
b = funkBox() #and another
a.funk("a") #call the function on the first instance
b.funk("b") # call the function again
a.show() # show what instance a has
b.show() # and b
Prints
['a', 'b']
['a', 'b']
Related
I am very new to python and I've been trying to do this code where i use a tkinter button command to run a function, it works but the append() is not executing, meaning it does not append to the list.
The list and the function containing the append is outside the class and is then classed within a class through the use of tkinter button command
I've tried putting the function inside the class, it works but the append is not adding into the list again.
This is the code I've made that is somewhat similar to real one
prices = []
f = True
class firstclass():
def __init__(self):
while f == True:
my_function()
f = False
def my_function():
prices.append(70)
class secondclass():
def __init__(self):
pass
print(sum(prices))
the sample of real code is in this link, please take this into consideration as well
python: Appending a value to a list outside the class, function with append also outside the class, but function is called within a class
I expected that it would print the appended value which is 70, but it still printed 0
A few issues you need to deal with. First assigning f=True outside the class won't change the value inside, so if you instantiated the class it would just throw an UnboundLocalError complaining that f isn't initialized. You can try this yourself by instantiating the class with
fc = firstclass()
Without instantiation, you have no hope of it giving you the value you want. It is printing zero because of the function secondclass, which has a print statement that is not contained within a method, so it prints the value sum(prices) which the class is declared. That value is from the original declared value of prices which is []. At least that is the way you have shown it in your question. I'm not sure whether you meant to indent the print statement, which would mean it is part of secondclass. However, if you didn't indent you would get the same result as you haven't instantiated firstclass.
To correct this, see below. This code will output 70 as you intended.
prices = []
class firstclass():
def __init__(self):
my_function()
def my_function():
prices.append(70)
class secondclass():
def __init__(self):
pass
print('before instantiation', sum(prices))
fc = firstclass()
print('after instantiation', sum(prices))
fc is now an object of type firstclass and the __init__ method has called my_function to append the value 70 to prices.
There are two reasons this is happening.
You never called firstclass to actually initialize the
constructor.
You are trying to assign False to the variable f
which does not belong to the scope of the class. If you still assign
it, it's considered local. And at the moment the interpreter
detects that you assigned it, the while loop does not have any local
reference of f since you did not define it under the constructor.
See this answer for more details.
Here is the completed code:
prices = []
class firstclass():
f = True
def __init__(self):
while self.f:
my_function()
self.f = False
def my_function():
prices.append(70)
class secondclass():
def __init__(self):
pass
firstclass()
print(sum(prices))
After reading this answer, I understand that variables outside of __init__ are shared by all instances of the class, and variables inside __init__ are unique for every instance.
I would like to use the variables that are shared by all instances, to randomly give my instance of the class a unique parameter. This is a shorter version of what I've tried;
from random import choice
class Chromosome(object):
variable1 = [x for x in range(1,51)]
variable2 = [x for x in range(51,101)]
def __init__(self):
self.var1 = choice(variable1)
self.var2 = choice(variable2)
My problem is that I can't reach the instance variables when initializing a new instance, the error message says name "variable1" is not defined, is there anyway to get around this?
EDIT: The reason I want to create the lists outside of the __init__ is to save memory, if I create 10.000 chromosomes with around 10-15 variables each, then it's better if I just create the lists once, instead of creating them for every chromosome.
EDIT2: If anyone wants to use it, my final solution involved using random.randrange(a,b+1,2). This picks out a random number (only even numbers) in the range [a,b], including the boundaries.
You just need to use the class name when referencing it. saying variable1 to Python will make it find a variable from the scope. However, your variable is an attribute of a class.
from random import choice
class Chromosome(object):
variable1 = [x for x in range(1,51)]
variable2 = [x for x in range(51,101)]
def __init__(self):
self.var1 = choice(Chromosome.variable1)
self.var2 = choice(Chromosome.variable2)
Equally, you could use self.variable1 since it is just an instance of the class and will have access to the class attributes too.
The main idea here is that when you access any attributes or methods of a class, you must provide an object which has access to these methods, be it the class, a subclass or an instance of either. You wouldn’t call dict.from_keys() as from_keys(), would you?
You could also just use self instead of Chromosome. Also object is not necessary I guess.
from random import choice
class Chromosome():
variable1 = [x for x in range(1,51)]
variable2 = [x for x in range(51,101)]
def __init__(self):
self.var1 = choice(self.variable1)
self.var2 = choice(self.variable2)
Here's another way: (the above answers are all true)
import random
class Chromosome(object):
def __init__(self):
self.var1 = random.choice([x for x in range(1, 51)])
self.var2 = random.choice([x for x in range(51, 101)])
I have a file that contains the class definitions and functions I need to use in my main file to make the text cleaner. However, I'm having a problem with imported global variables.
There is plenty of information at SO and other resources regarding how to make function variables global within the same code or how to use the global variables from an imported file. However, there is no information on how to access a variable from an imported file if the variable belongs to a function belonging to a class.
I would appreciate any help on how to do it or why it cannot be done. Please skip the lecture on the dangers of using global variables like this as my situation requires such use.
Edit: Sorry for not having an example in the original post. It's my first one. Below is an example of what I'm trying to accomplish.
Let's say I have a file classes.py that contains:
class HelixTools():
def calc_angle(v1, v2):
v1_mag = np.linalg.norm(v1)
v2_mag = np.linalg.norm(v2)
global v1_v2_dot
v1_v2_dot = np.dot(v1,v2)
return v1_v2_dot
Then in my main text file I do:
from classes import HelixTools
ht = HelixTools()
v1 = some vector
v2 = some other vector
ht.calc_angle(v1,v2)
print(v1_v2_dot)
The result is "v1_v2_dot" not defined. I need v1_v2_dot to use it as the input of another function.
Here's an example of how you can access class attributes (if I understand what it is you want to do correctly). Lets imagine you have a python file called "Test_class.py" that contains the following code:
class Foo(object):
def __init__(self, x, y):
self.x = x
self.y = y
def bar(self):
self.z = self.x + self.y
Now lets imagine you want to import this class into another python file in the same directory, and access attributes of that class. You would do this:
from Test_class import Foo
# Initialize two Foo objects
test1 = Foo(5, 6)
test2 = Foo(2, 3)
# Access the x and y attributes from the first Foo object
print(test1.x) # This will print 5
print(test1.y) # This will print 6
# Access the x and y attributes from the second Foo object
print(test2.x) # This will print 2
print(test2.y) # This will print 3
# Access the z attribute from the first Foo object
test1.bar()
print(test1.z) # This will print 11
# Access the z attribute from the second Foo object
test2.bar()
print(test2.z) # This will print 5
This works because variables defined in the __init__ magic method are initialized as soon as the Foo object is first called, so the attributes defined here can be access immediately after. The bar() method has to be called before you can access the z attribute. I made 2 Foo objects just to show the importance of including "self." in front of your variables, in that each attribute is specific to that particular class instance.
I hope that answers your question, but it would be very helpful if you provided some example code to show exactly what it is you want to do.
You should likely use a class attribute to store this value. Note that the implementation will depend on what your class HelixTools really does.
But for the example, you could use something like this:
import numpy as np
class HelixTools():
def __init__(self):
# Initialize the attribute so you'll never get an error calling it
self.v1_v2_dot = None
def calc_angle(self, v1, v2): # Pass self as first argument to this method
v1_mag = np.linalg.norm(v1)
v2_mag = np.linalg.norm(v2)
# Store the value in the attribute
self.v1_v2_dot = np.dot(v1,v2)
And then:
from classes import HelixTools
ht = HelixTools()
v1 = some vector
v2 = some other vector
ht.calc_angle(v1,v2) # This will not return anything
print(ht.v1_v2_dot) # Access the calculated value
I have seen many posts that shows how to access constant value, by inheritance. that's not my case.
I would like to create two instances from two different modules, and be able to share information/variables between them.
two issues:
1. the classes "dont know" each other, because they are on different files, "import"ing them as modules does not help much in this case
2. how can "print_class" instance can access & change values of variable in "cal_class" instance ?
Please note, I am looking for a way to access value from one instance to another. (in my case, there is allot of information (excel tables) to pass between instances, passing parameters through the "main" function is not practical)
Here is my simplify problem:
cal_class_file.py
class cal_class:
def add(self,first,second)
self.result= first + second
print_class_file.py
class print_class:
def print_sum(self):
result_from_cal_class = ?? <=-# How to get the value from local_calculate.result?
print(result_from_cal_class)
main.py
import cal_class_file
import print_class_file
def main():
local_calculate = cal_class_file.cal_class() # create instance
local_print = print_class_file.print_class(); # create instance that reads values from "local_calculate" instance
local_calculate.add(5,6) # calculate addition
local_print.print_sum() # output: 11
local_calculate.add(4,5) # update values in "local_calculate" instance
local_print.print_sum() # output: 9
How can I get the current (Latest) value for "result_from_cal_class" ?
Pass the value in. You have it right there in your client code:
class print_class:
def print_sum(self, result_from_cal_class):
print(result_from_cal_class)
def main():
local_calculate = cal_class_file.cal_class() # create instance
local_print = print_class_file.print_class(); # create instance that reads values from "local_calculate" instance
local_calculate.add(5, 6) # calculate addition
local_print.print_sum(local_calculate.result) # output: 11
local_calculate.add(4, 5) # update values in "local_calculate" instance
local_print.print_sum(local_calculate.result) # output: 9
Output:
11
9
However, if you mean that your client does this:
def main():
# setup elided ...
# actually call to add is done in another function
local_calculate.add(5, 6) # calculate addition
# actually call to print_sum is done somewhere else:
local_print.print_sum() # output: 11
You could define print_class like this:
class print_class:
def __init__(self, calculator):
self.calculator = calculator
def print_sum(self):
print(self.calculator.result)
Then initialise it like this:
def main():
local_calculate = cal_class_file.cal_class() # create instance
local_print = print_class_file.print_class(local_calculate); # create instance that reads values from "local_calculate" instance
Be careful as this is a little like having a global variable: calculate does something, leaving a result, print picks up the last result.
If you have an unexpected call to calculate between the one you want and the print, you will get unexpected results.
I'm still starting out how to program in Python, and I'm just wondering how to make a variable consistent throughout different functions. For example, a function that I've made modified a variable. Then, I've used that variable again in another function. How can I make the modified variable appear in the 2nd function? When I try it, the 2nd function uses the original value of the variable. How can you make it use the modified value? Do I need to use global variables for this?
Also, is the input() function recommended to be used inside functions? are there any side effects of using it inside them?
The variables need to be shared by a scope that is common to both functions, but this need not necessarily be a global scope. You could, for instance, put them in a class:
class MyClass:
def __init__(self):
self.x = 10
def inc(self):
self.x += 1
def dec(self):
self.x -= 1
mc = MyClass()
print mc.x # 10
mc.inc()
print mc.x # 11
mc.dec()
print mc.x # 10
What scope exactly the variable should exist in depends on what you're trying to do, which isn't clear from your question.
Use global variabale to access variable throughout code.
Demo:
>>> a = 10
>>> def test():
... global a
... a = a + 2
...
>>> print a
10
>>> test()
>>> print a
12
>>>
In class, use class variable which is access to all instance of that class. OR use instance variable which is access to Only respective instance of the class.
You can use return in the function.
x = 3
def change1():
x = 5
return x
x = change1()
def change2():
print(x)
change1()
change2()
You can use the global keyword at the top of the function to let python know that you are trying to modify the variable in global score. Alternatively, you could use OOP and classes to maintain an instance variable throughout class functions.
x = 5
def modify():
global x
x = 3
modify()