Class object is not defined [closed] - python

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.

Related

How to use any obtained variable from a function in other functions in Python classes? [closed]

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.

How to call a variable from inside a function within a class? [closed]

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)

Using self and parameters in a Python Script [closed]

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.

python - calling variable from another function [closed]

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

Import class in same file in Python [closed]

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()

Categories

Resources