Access class method variable outside of class
Yes there is, your existing code assigns 'something'
to x
, but this x
is actually not associated with the class instance. Change x = 'something'
to self.x = 'something'
does the trick.
class Person:
def do_something(self):
self.x = 'something'
person = Person()
person.do_something()
print(person.x)
# Prints 'something'
Refer to this answer if you want to know more about the subtleties of initializing class variables.
Accessing variable inside class from outside function in python
Updating values
by passing the list as an argument:
class A:
def insideclass(self):
values=[]
for i in range(10):
func(values)
def func(values):
now = datetime.time.now()
if now == "2021-06-25 10:15:52.889564":
# You can't compare a datetime to a string...
values.clear()
values.append(now)
You could throw an exception if the condition is met and perform the clear in the class method
class A:
def insideclass(self):
values=[]
for i in range(10):
try:
values.append(func())
except:
values.clear()
def func():
now = datetime.time.now()
if now == "2021-06-25 10:15:52.889564":
raise Exception('This should be a more specific error')
else:
return now
How to access a Variable or list or dictionary inside a method of a class, outside the class?
Like this:
class test:
def __init__(self):
self.ar = []
self.dict_t = {}
self.a = 0
print('inside the code')
def add(self, x, y):
self.a = x+y
def list_test(self):
self.ar.append(1)
self.ar.append(2)
def dict_test(self):
self.dict_t = {1: 2, 2: 3}
t = test()
t.list_test()
print(t.ar)
t.add()
print(t.a)
Note:
Define your variables in the initiate function.
Then you can access them through:
class_name.var_name
Accessing class variables outside the class in python
First you need to create an instance of the class, then you can use that instance to access its instance variable and function.
Below is a simple example based on your code
import tkinter as tk
class First:
def __init__(self, root):
self.root = root
self.root.title('First window')
self.root.geometry('1350x700+0+0')
self.mystring = tk.StringVar(self.root)
self.txt_id = tk.Entry(self.root, textvariable=self.mystring, font=("Times New Roman", 14), bg='white')
self.txt_id.place(x=200, y=400, width=280)
btn_search = tk.Button(self.root, text="Show in class", command=self.get_id)
btn_search.place(x=100, y=150, width=220, height=35)
def get_id(self):
val = self.mystring.get()
print("inside class:", val)
return val
root = tk.Tk()
# create an instance of First class
app = First(root)
def show():
# get the text from the Entry widget
print("outside class:", app.get_id())
tk.Button(root, text="Show outside class", command=show).pack()
root.mainloop()
Note that I have change class name from first
to First
because it is normal practise.
How to access variables of a method in a different class in Java?
In Java, variables declared inside a method have a scope limited to the method : they are not accessible outside of the method, even in the same class.
In that case, if you want to access them from outside, this means that their place is probably not as variables of the method, but as members of the class, ie "variables" declared as properties of the class, like this :
class Example {
public int field;
}
If you are referring to members, then whether you can access this field from outside the class depends on what you write in front of the field declaration :
public
: field will be accessible outside of the classprotected
: field will be accessible only in classes that extend this classprivate
: field will be accessible only inside that class
C++ Class - using public variables and defining member functions outside class
For 1.
, If f
is not declared in the class C
(that is, in C.h
), you cannot. you cannot add
a function to a class dynamically.
Also if is is declared in C.h
and also defined in C.cpp
, then you are attempting to duplicate its definition, you cannot as well.
If it is declared in C.h
and not defined in C.cpp
, you can define it here in the main's file, BUT this is not recommended (bad practice). Better put all the class's definitions of methods in its .cpp
file.
For 2, You can modify an attribute for an object of class C
if that member was declared in the public
section of the class:
class C {
... // private members
public: // public section
double x;
... // other public members, methods or attributes
};
In this case you can, in main:
C P;
P.x = 5.67;
Access a variable inside a class from outside the class
For this scenario you can use Object properties,
Define a public variable inside your class,
class Test(){
public $b;
function fun(){
$a= 0;
$this->b = 5;
$sum = $this->b+c;
return $sum;
}
}
$obj = new Test();
$b = $obj->b; // here null
echo $obj->fun();
$b = $obj->b; // here 5
Related Topics
Why Doesn't This Code Simply Print Letters a to Z
Type-Juggling and (Strict) Greater/Lesser-Than Comparisons in PHP
Generating a Single Entity from Existing Database Using Symfony2 and Doctrine
What Is an Abstract Class in PHP
Autoload Classes from Different Folders
Deleting a File After User Download It
Setting Up Laravel on a MAC PHP Artisan Migrate Error: No Such File or Directory
How to Compress/Decompress a Long Query String in PHP
Prevent Direct Url Access to PHP File
Double Not (!!) Operator in PHP
Getting the First Character of a String with $Str[0]
PHP Is Not Recognized as an Internal or External Command in Command Prompt