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.
Related
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 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
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 8 years ago.
Improve this question
I'm new to python and trying to write a python script that would take two command line arguments, do something to them, and return the output back to the stdout.
My script is like this:
class MyClass:
def GET(self):
#get the passed in arguments in arg1 and arg2
return self.perform(arg1, arg2)
def perform(self, arg1, arg2):
return arg1+arg2
if __name__ == "__main__":
#call the GET method of MyClass with all the arguments
How can I pass the command line arguments sys.argv[1:] to GET method of MyClass?
Will the signature of GET change from GET(self) to GET(self, arg1, arg2)?
What you've written there is instance methods, which need an instance for you to call them on.
E.g.
x = MyClass() # create an instance of MyClass
x.GET()
However, arg1 and arg2 are never initialised, so your GET method won't know what they are. If you want to pass them into GET you would need to specify them as parameters:
class MyClass:
def GET(self, arg1, arg2):
...
and then you could call the method with
x.GET(sys.argv[1], sys.argv[2])
but that would make GET kind of pointless, since all it does is redirect the call to the perform method.
If you prefer, you could pass the argv array itself to GET. That would require:
class MyClass:
def GET(self, args):
return self.perform(args[1], args[2])
...
x = MyClass()
x.GET(sys.argv)
If you want to output the result to stdout, you would use print. E.g.
print(x.GET(sys.argv))
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 9 years ago.
Improve this question
I'm trying to reference class object inside another class. In the sample code below, I want to be able to call Class1 methods from Class3, but they must be created in order where Class1(ClassObject) creates Class2 and Class2 creates Class3. Class3 must be then able to call ClassObject.
Code below gives not defined error.
NameError: global name 'ClassObject' is not defined
Any workarounds or fixes to this problem?
class Class1:
def __init__(self):
Class2()
def method(self):
print("test")
class Class2:
def __init__(self):
Class3()
class Class3:
def __init__(self):
ClassObject.method()
ClassObject = Class1()
Assignment are executed right to the left. It means that Class1() is computed before ClassObject is defined.
Before the affectation, the global scope looks like ['Class1', 'Class2', 'Class3'].
So the following stack happens:
"Class1()" is called -> get Class1 reference in the global scope
Class1.__init__
-> "Class2()" is called -> get Class2 reference in the global scope
-> Class2.__init__
-> "Class3()" is called -> ... you might know now.
-> Class3.__init__
-> ClassObject.method()
-> try to get ClassObject from global scope
-> raises exception: ClassObject isn't defined
Inde
I would like to give you a valid code, but your 3 classes haven't any meanings...
When Class1() is called there is no ClassObject global variable.
Since in python there are no variable declarations, the variable can be accessed only when it is defined, which means when it has a value. In your case the value would the that instance, but that instance is trying to reference the global variable before the assignment is complete.
If you want to reference the object in the assignment you must use self. However, in your code Class3 doesn't have any access to the Class1 instance so you'll get a different error.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm new to python and I have a file with several classes. In a method in the class "class1" I want to use a method from another class "class2". How do I do the import and how do I call the method from class1? I have tried several different things but nothing seems to work.
You don't need to import them, because they are already in the same file.
Instead, do something like this:
class1 = Class1() #assigns class1 to your first class
Then call a method inside of Class1 like this:
Class2():
def method2(self):
class1.method1() #call your method from class2
Basically you are taking Class2() and pointing it to the instance class2, then you are calling a method of that class by doing class2.method2(). It's just like calling a function from the current class, but you use instance name in front of it.
Here is an example:
class Class1():
def method1(self):
print "hello"
class Class2():
def method2(self)
class1 = Class1()
class1.method1()
Then, when you call Class2() it will print 'hello'.
Let's say your file with all the classes is called myclass.py with the following:
class Class2(object):
def foo(self):
return 'cabbage'
class Class1(Class2):
def bar(self):
return self.foo()
In your main script, you can import the module as usual:
import myclass
And now you can create an instance of class1:
myinstance = myclass.Class1()
Then you can call the function directly:
myinstance.bar()
# Returns 'cabbage'
If all of the classes are in the same file, you don't need to import them. They are in the module scope already. Here's an example:
class A():
def print_one(self):
print "one"
class B():
def print_two_and_one(self):
print "two"
A().print_one()
B().print_two_and_one()