I'm making a python app and I have a class with a function that changes a variable created after the class. I can't put that variable before the class because that variable refers to variables inside the class and I end up with a paradox. It looks something like this:
class LeClass:
def __init__(self):
#Casual__init__Stuff
def LeFunction(self):
A = 1
A = LeClass()
Anyone got a solution? Thanks!
Declare the variable A global before assigning it from within your class code:
global A
A = 1
Otherwise, A will be a local variable that goes out of scope (is not accessible anymore) after the method returns.
Just tell python to look for the variable outside the class first when you try to use that variable.
Here is the code :
class LeClass:
def __init__(self):
pass
#Casual__init__Stuff
def LeFunction(self):
global A
A = 1
A = LeClass()
print("First Print :", A)
A.LeFunction()
print("Second Print :", A)
And here is the output of the code :
First Print : <__main__.LeClass object at 0x7f2ba3f1bb38>
Second Print : 1
Related
Here is the question of a python code asked on InfyTQ mock test.
class classOne:
__var_one = 1001
def __init__(self,var_two):
self.__var_two = var_two
self.__var_five = 5
def method_one(self):
var_four = 50
self.__var_five = ClassOne.__var_one + self.__var_two + var_four
Now, I want to ask if the variable
self.__var_five of function method_one should be considered a new instance variable or not?
Because there is already a self.__var_five in __init__ function.
Also,
I learned the concept of global,local,static and instance variable from given below code.
Is it correct?
#global, local, static, instance variable.
#global variable are defined at the top of program or defined using keyword:global
global global_var1 = 0
global_var2 = 1
def local_variable:
#local variable are defined inside of a function.
local_var1 = 2
class static_instance:
#static/classs variable are defined inside of a class.
static_var1 = 3
def __init__(self):
#all variables defined in the function of a class starting with self.
self.instance_var1 = 4
def static(self):
self.instance_var2 = 5
local_var2 = 6 #local variable as it is in a function.
static_var2 = 6
It's the same instance variable (called an attribute in Python). method_one is simply updating its value.
Most of your understandings in the second code block are correct. However, when a method does:
self.static_var1 = 4
it creates an instance attribute named static_var1. This is independent of the class attribute that was declared outside the methods, which is shared among all instances that don't reassign it. But since you do the assignment in the __init__() method, all instances get their own attribute. The only way to access the static value would be with static_instance.static_var1.
How to access an outer class member from an inner class in Python 3?
Below is my code snippet.
class Outer:
def __init__(self):
self.__x = 20
self.__str = "Outer Class"
def show(self):
self.i1 = self.Inner(Outer())
self.i1.display()
def fn(self):
print("Hello from fn() of Outer Class")
print("str : ", self.__str)
class Inner:
def __init__(self, outer):
self.__str_in = "Inner Class"
self.outer = outer
def display(self):
print("str_in : ", self.__str_in)
print("Inside display() of Inner Class")
# print("x : ", self.outer.__x)
# print("str : ", self.outer.__str)
# self.outer.fn()
obj = Outer()
obj.show()
If I execute the commented lines, it throws an error saying -
line 23, in display
print("x : ", self.outer.__x)
AttributeError: type object 'Outer' has no attribute '_Inner__x'
Can anyone help? Thanks in advance.
The problem with your code is that you didn't understand correctly the meaning of name mangling, that's exactly what you're doing when adding the double leading score in your variable name.
When setting up the variable as self.__x, what you're actually doing is telling the world outside your class that it can only be accessed this way when operating inside the Outer class. If you try to access outside, lets say add after the definition of obj the following print(obj.__x), you'll see the same problem.
The name mangling means that when accessing the variable outside of the scope of your class, you should call the variable _ClassName__variableName, so, in our example, you should use print(obj._Outer__x) to be able to print the variable.
Since your Inner class works the same way, as an outside scope, the simplest solution would be to rewrite your display method this way:
def display(self):
print("str_in : ", self.__str_in)
print("Inside display() of Inner Class")
print("x : ", self.outer._Outer__x)
print("str : ", self.outer._Outer__str)
self.outer.fn()
Now, other thing I noticed, and can generate problems if you didn't do this consciously, is the call self.i1 = self.Inner(Outer()). Here you're not using the same object data that you instantiated as obj, but creating a new instance of Outer and sending this to Inner.
And what's the problem with this?
Let's say you added the following lines:
obj = Outer()
obj._Outer__x = 10
obj.show()
Then the output of your show() will always be x: 20, because this change you've done in the variable, was made to an instance that was not passed to Inner.
If it's not the behaviour you were aiming for, just change this line to:
self.i1 = self.Inner(self)
So now you're effectively passing the instantiated object to Inner
The problem is that you are passing the class instead of an instance in self.i1 = self.Inner(Outer), and self.__str is an instance attribute.
There is also another problem. You are using __ prefix which is subjected to name mangling, so try to avoid that.
You have 2 ways to fix this:
Pass the instance, ie self.i1 = self.Inner(self)
or
Make _str a class attribute:
class Outer:
_str = "Outer Class" # NOTE THE SINGLE _
def __init__(self):
self._x = 20 # NOTE THE SINGLE _
...
We are facing a problem in accessing member attributes of a class when we the member attribute name is stored in another variable. For example : We have a class A, which has member attributes is var1, var2, var2, and upto var 100. From another class, we are trying to access var67, the name of attribute we want to access ( i.e. var67) is stored in a different variable x, as a string ("var67")(this x is generated from a different function). So from the value of x how can we access var67 attribute as we just can't do A.x . Please guide us any short approach other than building a method in class A to access variables in such case. Thanks!
MyClass:
variable = "blah"
def function(self):
print("This is a message inside the class.")
myobjectx = MyClass()
x="variable"
myobjectx.(getattr(MyClass(), x))
The last line will throw a syntax error
In python you have the getattr builtin function:
class A:
def __init__(self):
self.a67 = 10
x = "a67"
print(getattr(A(), x))
Here you have a live example
Here is some example code for the question:
class Obj():
def __init__(self, p):
self.property = p
def printProp(self):
print(self.property)
myVar = 0
myObject = Obj(myVar)
myObject.printProp()
myVar = 1
myObject.printProp()
When this runs, the parameter is not changed, and 0 is printed twice, because the constructor is only called once. Is there a way to have the property always directly reference the myVar variable?
You can access the classes property directly like this: myObject.property = 1.
Alternatively, you could add a class method to set the property like this:
def setProp(self, val):
self.property = val
This is generally better coding practice as class properties should only be modified within the class.
In order to create a code, I have decided to create a python class to just define some variables with default value. you can see this as "struct" in C.
the file is name : ScreenStructure.py
Inside I have defined this code
class ViewIdleScreen():
def _init_(self):
self.menu_access = "id/no_id/21"
self.Call_app = "id/no_id/23"
self.Email_app = "idno_id/24"
self.Camera_app = "id/no_id/27"
self.Browser_app = "id/no_id/26"
self.Contacts_app = "id/no_id/9"
self.Calendar_app = "id/no_id/10"
self.Messaging_app = "id/no_id/11"
self.Notes_app = "id/no_id/12"
def Call_app(self):
return self.Call_app
In the main file, I have added :
from ScreenStructure import ViewIdleScreen
later in the code of the main file:
IdleScreenView = ViewIdleScreen()
print IdleScreenView.Call_app()
but instead of displaying "id/no_id/23" it display
<bound method ViewIdleScreen.Call_app of <ScreenStructure.ViewIdleScreen instance at 0x02A16990>>
First, you're naming __init__ _init_. This is wrong. You need two underscores.
Second, you're setting an attribute Call_app there, but that's the same name as the method you define later:
def Call_app(self):
return self.Call_app
In addition to being shadowed by the attribute (if __init__ were declared properly), this method returns the method itself, which is the bound method you're seeing.
Avoid the collision of attribute and method names, and name __init__ correctly
you should not make functions named the same as data members
hello = "hello world"
def hello():
print "goodbye!"
print hello
often times people will make a variable name preceded by an underscore or something
class X:
def __init__(self,*args):
self._x = "yellow"
def x(self):
return self._x
but as #mhlester points out a main problem is that you named __init__ incorrectly