Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
iam working on tkinter iam using filedialog to upload file my target is to have tow button.
button1 for uploading txt file
button2 is for processing the file see my current function setup
class procFile:
def uploadFile(self, filename):
self.filename = filename
def displayName(self):
return self.filename
def filePath(self):
print("%s" %self.filename)
def main():
upload = procFile()
upload.uploadFile(filedialog.askopenfilename(filetypes=(('txt', '*.txt'), ('All Files', '*.*'))))
upload.filePath()
Please i need to another button to fireup another function which will access the variable from main function
Although your question is dull in providing detail, here are two ways that results to what I understood of your question.
Method 1
If you want to access the class variable in a function outside the class then:
class Class:
# do something
# example:
def __init__(self):
self.var = 2
print(self.var)
def outsideFunc():
# operations you want to do
# example:
print(a.var * 3)
Result
>> a = Class()
2
>> outsideFunc()
6
Note that outsideFunc() can be defined anytime during the program. However, you can only call outsideFunc() after the class has been initialized.
The reason for this is because filepath is an instance of the class procfile which is only defined once the class is initialized. The period after the initialized class can be followed by various objects such as a function Class.func(), a variable Class.var or even a nested class Class.subClass
Method 2
If you want to access the class variable inside the class then:
class Class:
# do something
# example:
def __init__(self):
self.var = 4
print(self.var)
def func(self):
# operations you want to do
# example
print(self.var + 5)
Result
>> b = Class()
4
>> b.func()
9
Just do the same what you have done before which is accessing the variable through self.var in the class.
Compare
Method 1 requires that when you call the class variable in an outside function, it has to be the same as the variable name you used to initialize the class. So when you do a = Class(), any function outside the class that refers to the initialized class will have to do a.object where object can be function, variable, or subclass.
Method 2 requires the same thing. However, when the function inside the class is referring to one of it's variables, then it needs to use self.object where object can be function, variable, or subclass.
Both require that you initiate the class first with varName = className() in which varName is just a variable used to reference the class. Afterwards, you do as before with varName.object
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 21 days ago.
Improve this question
I am trying to use one variable obtained from one function in other function. However , it gives error. Let me explain it wih my code.
class Uygulama(object):
def __init__(self):
self.araclar()
self.refresh()
self.gateway_find()
def refresh(self):
self.a, self.b = srp(Ether(dst="FF:FF:FF:FF:FF:FF") / ARP(pdst=self.ip_range2), timeout=2, iface="eth0",
retry=3)
#There are unrelated codes here
def gateway_find(self):
#Find ip any range in which you conncet:
self.ip_range=conf.route.route("0.0.0.0")[1]
self.ip_range1=self.ip_range.rpartition(".")[0]
self.ip_range2=self.iprange_1+".0/24"
When , run the foregoing codes , i get this error AttributeError: 'Uygulama' object has no attribute 'ip_range2'
How can i use such variable which are obtained from other function in the other function. How can i fix my problem ?
Call order of init functions
Place function that define attribute first
In the __init__ function, you call refresh, who use (need) ip_range2 before gateway_find who create the attribute and set a value to it. Swap the two lines, you should be fine.
def __init__(self):
self.araclar()
self.gateway_find() # gateway_find will set the ip_range attribute
self.refresh() # So refresh function will be able to access it
Usually, we place init functions first, then function that will call post-init processes like refresh.
Class attribute default value
Alternatively, you can define a default value for ip_range2 like this:
class Uygulama(object):
ip_range2 = None
def __init__(self):
self.araclar()
self.refresh()
self.gateway_find()
def refresh(self):
self.a, self.b = srp(Ether(dst="FF:FF:FF:FF:FF:FF") / ARP(pdst=self.ip_range2), timeout=2, iface="eth0", retry=3)
Be aware that such default value is shared with all other instances of the class if not redefined in __init__, so if it's a mutable (like a list), it might create really weird bugs.
Usually, prefer defining value in the __init__ like you do with the gateway fct.
That error explains correctly that you do not have a class attribute called ip_range2. You need to define the class attribute first.
class Uygulama(object):
ip_range2 = ''
...
then use that with self.ip_range2.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I want to call a variable created in a function (func) that is also in a class (A). Below is a very basic version of what I want to accomplish in my larger code. I am fairly new to coding so any help would be appreciated.
class A:
def func(self):
self.number = 1
print(A.number)
You need to read about static var : (copy/paste)
ref: https://www.geeksforgeeks.org/g-fact-34-class-or-static-variables-in-python/
You can run the code there to understand more
Class or Static Variables in Python
Class or static variables are shared by all objects. Instance or non-static variables are different for different objects (every object has a copy of it).
For example, let a Computer Science Student be represented by class CSStudent. The class may have a static variable whose value is “cse” for all objects. And class may also have non-static members like name and roll.
In C++ and Java, we can use static keyword to make a variable as class variable. The variables which don’t have preceding static keyword are instance variables. See this for Java example and this for C++ example.
The Python approach is simple, it doesn’t require a static keyword. All variables which are assigned a value in class declaration are class variables. And variables which are assigned values inside class methods are instance variables.
# Python program to show that the variables with a value
# assigned in class declaration, are class variables
# Class for Computer Science Student
class CSStudent:
stream = 'cse' # Class Variable
def __init__(self,name,roll):
self.name = name # Instance Variable
self.roll = roll # Instance Variable
# Objects of CSStudent class
a = CSStudent('Geek', 1)
b = CSStudent('Nerd', 2)
print(a.stream) # prints "cse"
print(b.stream) # prints "cse"
print(a.name) # prints "Geek"
print(b.name) # prints "Nerd"
print(a.roll) # prints "1"
print(b.roll) # prints "2"
# Class variables can be accessed using class
# name also
print(CSStudent.stream) # prints "cse"
CSStudent.stream = "foo"
print(a.stream) # prints "foo" (this variable litterally is CSStudent.stream)
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
If I have an object, and within that object I've defined a variable, which of these methods would be considered 'best' for accessing the variable?
Method One
Using a getter function
class MyClass:
def __init__(self):
self.the_variable = 21 * 2
def get_the_variable(self):
return self.the_variable
if __name__ == "__main__"
a = MyClass()
print(a.get_the_variable())
Method Two
Using the #property decorator
class MyClass:
def __init__(self):
self._the_variable = 21 * 2
#property
def the_variable(self):
return self._the_variable
if __name__ == "__main__"
a = MyClass()
print(a.the_variable)
Method Three
Simply accessing it directly
class MyClass:
def __init__(self):
self.the_variable = 21 * 2
if __name__ == "__main__"
a = MyClass()
print(a.the_variable)
Are any of these methods more pythonic than the others?
Method 3 is the standard pythonic way to start. If you need additional logic, filtering or some other behavior for the attribute you can always go back and add a method for the attribute and use the #property decorator at a later time. That's the beauty of python, start with something simple that works. If you later need finer control over the attribute you can create the property and not have to update/change any of the client code that uses the attribute. The client code will not know the difference between accessing the attribute directly vs calling a method and as a result does not have to change.
This ideology is confirmed via PEP 549
Python's descriptor protocol guides programmers towards elegant API design. If your class supports a data-like member, and you might someday need to run code when changing the member's value, you're encouraged to simply declare it as a simple data member of the class for now. If in the future you do need to run code, you can change it to a "property", and happily the API doesn't change.
I think it's not easy to answer since it's based on the program.
class MyClass:
def __init__(self):
self.the_variable = 21 * 2
def get_the_variable(self):
return self.the_variable
But if you want to pass a class attirubete to some variable, I think it's better to use getter-setter, since it is more readable and understandable. Because you are basically telling I ask this value. For example:
if __name__ == "__main__":
a = MyClass()
modified_variable = a.get_the_variable() * 2
In contrary, if you are just using that class attribute, third option a.the_variable is better.
if a.get_the_variable() == 42:
# do something
else:
# do something
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I'd like to use self (for global variables) and the parameters from the command-line in my Python Script but can't really get them to work.
def otherFunction(self)
print self.tecE
def main(argv,self):
self.tecE = 'test'
otherFunction()
if __name__ == "__main__":
main(sys.argv[1:],self)
This gives me an error:
main(sys.argv[1:],self)
NameError: name 'self' is not defined
So how and where to define self?
Usually the python convention of self is to be used in python classes, you did a bit of a mess.
So either you are not using classes and treating self just as a global dict, like this:
import sys
myglobal = {} # Didn't want to name it self, for avoiding confusing you :)
def otherFunction():
print myglobal["tecE"]
def main(argv):
myglobal["tecE"] = 'test'
otherFunction()
if __name__ == "__main__":
main(sys.argv[1:])
Or writing a class, like this:
import sys
class MyClass():
def otherFunction(self):
print self.tecE
def main(self, argv):
self.tecE = 'test'
self.otherFunction() # Calling other class members (using the self object which actually acting like the "this" keyword in other languages like in Java and similars)
if __name__ == "__main__":
myObj = MyClass() # Instantiating an object out of your class
myObj.main(sys.argv[1:])
So how and where to define self?
You will use self:
As the first argument of your class methods def my_method(self, arg1, arg2):
Within the class to refer to any other class members (just as demonstrated above) self.do_job("something", 123)
For creating class members: self.new_field = 56 Usually in __init__() constructor method
Note: decalring a class variable without the self.new_var, will create a static class variable.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I just rewrote a working program into functions in a class and everything messed up.
First, in the __init__ section of the class I declared a bunch of variables with self.variable=something.
Should I be able to access/modify these variables in every function of the class by using self.variable in that function? In other words, by declaring self.variable I have made these variables, global variables in the scope of the class right?
If not, how do I handle self?
Second, how do I correctly pass arguments to the class?
Third, how do I call a function of the class outside of the class scope?
Fouth, how do I create an Instance of the class INITIALCLASS in another class OTHERCLASS, passing variables from OTHERCLASS to INITIALCLASS?
I want to call a function from OTHERCLASS with arguments from INITIALCLASS. What I've done so far is.
class OTHERCLASS():
def __init__(self,variable1,variable2,variable3):
self.variable1=variable1
self.variable2=variable2
self.variable3=variable3
def someotherfunction(self):
something=somecode(using self.variable3)
self.variable2.append(something)
print self.variable2
def somemorefunctions(self):
self.variable2.append(variable1)
class INITIALCLASS():
def __init__(self):
self.variable1=value1
self.variable2=[]
self.variable3=''
self.DoIt=OTHERCLASS(variable1,variable2,variable3)
def somefunction(self):
variable3=Somecode
#tried this
self.DoIt.someotherfunctions()
#and this
DoIt.someotherfunctions()
I clearly didn't understand how to pass variables to classes or how to handle self, when to use it and when not. I probably also didn't understand how to properly create an instance of a class. In general I didn't understand the mechanics of classes so please help me and explain it to me like I have no idea (which I don't, it seems). Or point me to a thorough video, or readable tutorial.
All I find on the web is super simple examples, that didn't help me much. Or just very short definitions of classes and class methods instances etc.
I can send you my original code if you guys want, but its quite long.
class Foo (object):
# ^class name #^ inherits from object
bar = "Bar" #Class attribute.
def __init__(self):
# #^ The first variable is the class instance in methods.
# # This is called "self" by convention, but could be any name you want.
#^ double underscore (dunder) methods are usually special. This one
# gets called immediately after a new instance is created.
self.variable = "Foo" #instance attribute.
print self.variable, self.bar #<---self.bar references class attribute
self.bar = " Bar is now Baz" #<---self.bar is now an instance attribute
print self.variable, self.bar
def method(self, arg1, arg2):
#This method has arguments. You would call it like this: instance.method(1, 2)
print "in method (args):", arg1, arg2
print "in method (attributes):", self.variable, self.bar
a = Foo() # this calls __init__ (indirectly), output:
# Foo bar
# Foo Bar is now Baz
print a.variable # Foo
a.variable = "bar"
a.method(1, 2) # output:
# in method (args): 1 2
# in method (attributes): bar Bar is now Baz
Foo.method(a, 1, 2) #<--- Same as a.method(1, 2). This makes it a little more explicit what the argument "self" actually is.
class Bar(object):
def __init__(self, arg):
self.arg = arg
self.Foo = Foo()
b = Bar(a)
b.arg.variable = "something"
print a.variable # something
print b.Foo.variable # Foo
So here is a simple example of how to use classes:
Suppose you are a finance institute. You want your customer's accounts to be managed by a computer. So you need to model those accounts. That is where classes come in. Working with classes is called object oriented programming. With classes you model real world objects in your computer. So, what do we need to model a simple bank account? We need a variable that saves the balance and one that saves the customers name. Additionally, some methods to in- and decrease the balance. That could look like:
class bankaccount():
def __init__(self, name, money):
self.name = name
self.money = money
def earn_money(self, amount):
self.money += amount
def withdraw_money(self, amount):
self.money -= amount
def show_balance(self):
print self.money
Now you have an abstract model of a simple account and its mechanism.
The def __init__(self, name, money) is the classes' constructor. It builds up the object in memory. If you now want to open a new account you have to make an instance of your class. In order to do that, you have to call the constructor and pass the needed parameters. In Python a constructor is called by the classes's name:
spidermans_account = bankaccount("SpiderMan", 1000)
If Spiderman wants to buy M.J. a new ring he has to withdraw some money. He would call the withdraw method on his account:
spidermans_account.withdraw_money(100)
If he wants to see the balance he calls:
spidermans_account.show_balance()
The whole thing about classes is to model objects, their attributes and mechanisms. To create an object, instantiate it like in the example. Values are passed to classes with getter and setter methods like `earn_money()´. Those methods access your objects variables. If you want your class to store another object you have to define a variable for that object in the constructor.
The whole point of a class is that you create an instance, and that instance encapsulates a set of data. So it's wrong to say that your variables are global within the scope of the class: say rather that an instance holds attributes, and that instance can refer to its own attributes in any of its code (via self.whatever). Similarly, any other code given an instance can use that instance to access the instance's attributes - ie instance.whatever.