my global can't change in the def of a class [duplicate] - python

This question already has answers here:
Using global variables in a function
(25 answers)
Closed 3 years ago.
I define a varible, name 'Decisoin_name' and set -1 at first
and I try to change it in a def of a class
because I’d like to add 1 everytime when I call the def
but the system send me a message
"local variable 'Decision_name' referenced before assignment"
what can I do?
Would you give me a solution to fix it ? thank you
The following is my code
Decision_name = -1
class Decision_Dialog(QDialog):
def sendback(self):
Decision_name+=1
print(Decision_name)
self.close()

You can't change a global name from a class method directly, you need to declare it as a global variable beforehand:
class Decision_Dialog(QDialog):
def sendback(self):
global Decision_name
Decision_name += 1
Although if it does not need to be a global variable, you can take different routes e.g. make it a class variable and let each instance modify to it's need, or make it a instance variable by defining in __init__ and make necessary changes afterwards.
Also, you should be using snake_case for variable names e.g. decision_name.

Related

What's the point of creating classes and self in python? [duplicate]

This question already has answers here:
When should I be using classes in Python?
(6 answers)
What is the purpose of the `self` parameter? Why is it needed?
(26 answers)
Closed 8 months ago.
What's the point of creating classes and self in python? Like:
class ThisIsClass(self):
def Func():
self.var+=1
ThisIsClass()
Is it necessary to use them?
It becomes necessary to pass self argument to the functions of your class. however, your code has several problems like the initialization of var variable. You need a constructor __init__ to create the variable, after that, you will be able to modify it:
class ThisIsClass:
def __init__(self, value=0):
self.var = value
def Func(self):
self.var+=1
c = ThisIsClass()
c.Func()
print(c.var)
In the above code, the class is instantiated as an object and stored in the variable c. You can assign an initial value to var by passing an argument to the object creation, like: c = ThisIsClass(89)
Output:
1
It has to do with the right structure of programming in python. No you dont need them 100% but if you want to have a nice and clean code I would propose you to get used of them. Also when the self is declared inside the brackets after the function name, that function can retrieve (and make available) the variable (self.variable) from and to wherever inside that class.

Call an object that was created in a function from outside that function [duplicate]

This question already has answers here:
What is the purpose of the return statement? How is it different from printing?
(15 answers)
Closed 1 year ago.
Use case is simple: I create an object from a class in Python. If I create that object outside of any function, I have no problem getting back any of the attributes.
But somehow if I happened to create that object inside a function, I cannot get it back anywhere.
This works:
class UserTest():
def__init__(self,name,age,size):
self.name=name
self.age=age
self.size=size
FirstUser=UserTest(name,age,size)
print(FirstUser.name,FirstUser.age,FirstUser.size)
But this does not:
class UserTest():
def__init__(self,name,age,size):
self.name=name
self.age=age
self.size=size
def createUser(name,age,size):
FirstUser=Usertest(name,age,size)
return FirstUser
createUser('Max',38,180)
print(FirstUser.name,FirstUser.age,FirstUser.size)
And I cannot figure why I cannot find the object I just created, even if I return the FirstUser object at the end of the function.
What am I missing?
Any variable assignment changes the scope of the variable to the current code block.
This means, in your code the variable FirstUser is only known inside createUser.
To use FirstUser as a global variable, you could use the global keyword:
def createUser(name,age,size):
global FirstUser
FirstUser=UserTest(name,age,size)
return FirstUser
createUser('Max',38,180)
print(FirstUser.name,FirstUser.age,FirstUser.size)
or even better: do not use global variables, but work with the return value:
def createUser(name,age,size):
return UserTest(name,age,size)
FirstUser = createUser('Max',38,180)
print(FirstUser.name,FirstUser.age,FirstUser.size)
Object returned by createUser('Max',38,180) has to be assigned or cached into a reference variable which can then be used to call its members, like such
user = createUser('Max',38,180)
then this reference variable user can be used to call its members.
The returned value from createUser is not assigned
You also have some typos : missing spaces and case
Input:
class UserTest():
def __init__(self,name,age,size):
self.name=name
self.age=age
self.size=size
def createUser(name,age,size):
return UserTest(name,age,size)
## ANSWER CORE ##
firstUser = createUser('Max',38,180)
print(firstUser.name,firstUser.age,firstUser.size)
Output:
Max 38 180

How can I emulate passing a variable by reference to an object in Python? [duplicate]

This question already has answers here:
How do I pass a variable by reference?
(39 answers)
Closed 2 years ago.
I want to create a Python class that can:
Take a variable as an argument when instantiating
Store the value of the variable in an attribute
Store the current value of the variable whenever "update()" method is used.
The code below did not work as intended. How can I update the value of the attribute through a method call, keeping in mind that it must work for arbitrary variables?
class MyObject():
def __init__(self,data):
self.data = data
def update(self):
self.data = data
value = 0
dataobject = MyObject(value)
value = 1
dataobject.update() #NameError: name 'data' is not defined
Pass by reference doesn't work the way you want in Python for int and other basic types (different story for lists and other types of objects, but I'll just answer the question you asked).
I don't really recommend this approach, but you could do this with the Global keyword:
class MyObject():
def __init__(self,data):
self.data = data
def update(self):
global value # only change is this
self.data = value
value = 0
dataobject = MyObject(value)
value = 1
dataobject.update()
print(dataobject.data) # prints 1
objects in Python don't have private attributes, so you could directly set the value:
dataobject.data = 1
Neither of these strike me as best practices, but I would have to know more about what you are trying to do in order to give you the best advice. Note that if you plan on having a bunch of instances of MyObject, trying to sync them up with a single global value may get out of hand. I would advise a new question with more info about what you are trying to do and someone will give the the best approach.

How to access variables in a function from another function of same class? [duplicate]

This question already has answers here:
How to share variables between methods in a class? [duplicate]
(2 answers)
Closed 3 years ago.
Here's an example for explaining my question a little better,
class T:
def fn(self):
rest = 'test'
return rest
def fn1(self):
print(rest)
I want to know, if there's any way that I can access the variable defined in functionfn in function fn1.
I looked around and I found that we could make variable global by passing global rest in function fnlike below,In this way I was able to access rest variable in function fn1
def fn(self):
global rest
rest = 'test'
return rest
I want to know if there are any other way that I can access variables across multiple functions all belonging to same class.
Any help is really appreciated, Thanks.
Use attributes:
class TheClass:
def __init__(self):
self.rest = None
def set_rest(self):
self.rest = "test"
def print_rest(self):
print(rest)
instance = TheClass()
instance.set_rest()
instance.print_rest()

Are Class variables mutable? [duplicate]

This question already has answers here:
Class (static) variables and methods
(27 answers)
What is the difference between class and instance attributes?
(5 answers)
Closed 5 years ago.
If I define a simple class
class someClass():
var = 1
x = someClass()
someClass.var = 2
This will make x.var equal 2. This is confusing to be because normally
something akin to this like:
a = 1
b = a
a = 2
will leave b intact as b==1. So why is this not the same with class variables? Where is the difference? Can call all class variables mutable?
In a way the class variables work more like assigning a list to a=[1] and doing a[0]=2.
Basically the problem is how is x.var acessing someClass.var it must be something different then is used when two variables are set equal in python. What is happening?
var is a static class variable of someClass.
When you reach out to get x.var, y.var or some_other_instance.var, you are accessing the same variable, not an instance derived one (as long as you didn't specifically assigned it to the instance as a property).

Categories

Resources