Im writing a GUI with Tkinter in python 2.7 where i want a username variable to get used in another class. This is my first time doing OOP, so i'm not good at all. All help is appreciated.
Here is a link of the full code.
class LoginWindow(Frame):
def logged(self):
username = self.entry_username.get()
password = self.entry_password.get()
class MainWindow(Frame):
def saveValues(self):
# I WANT THE USERNAME VARIABLE HERE #
You can define username and password as global variable outside all the classes and then use them directly in whatever class you want.
Now for your code, you can try this too:
class LoginWindow():
def __init__(self):
self.username = self.entry_username.get()
self.password = self.entry_password.get()
class MainWindow():
def saveValues(self):
obj = LoginWindow()
# Access the object's variables here
print(obj.username, obj.password)
return "Done..."
print(MainWindow().saveValues())
This will print
("whatever_username", "password")
Done...
Related
I have checked lots of websites and almost all questions related to the same on Stackoverflow. I cant find the solution to this problem. Its very important for a project. Please help. I want to use the variable self.email in Class A in the function email(self) in Class B. I've tried several things, but its not working. Inheritance wont work because its a kivy-python code and its already inheriting classes like GridLayout().
Class A:
def __init__(self):
---some code---
def email_id(self):
self.email = x
Class B:
def __init__(self):
print(A().email)
I think what you might be looking for are property decorators
Class A:
def __init__(self):
---some code---
#property
def email(self):
return (some code to show the email)
The field email of class A is created when email_id() is called.
Therefore, by the time print(A().email) is executed, this field is still not set.
You can set it first
Class B:
def __init__(self):
a = A()
a.email_id("email")
print(a.email)
I'm trying to access the currently logged in user eslewhere in my code (i.e in other classes). I've managed to do this to some extent with global (frowned upon I know but didn't find any other way), as shown below:
class Login(Screen):
def login(self, email, password):
try:
global user
user = auth.sign_in_with_email_and_password(email, password)
print(user['localId']) #This is the users uid
class SelectChat(Screen):
def __init__(self, **kwargs):
super(SelectChat, self).__init__(**kwargs)
grid = GridLayout(cols=1)
self.add_widget(grid)
docs = db.collection(u'users').where(u'value', u'==', True).stream()
for doc in docs: # cycle through database and create Buttons for each value found
dict = doc.to_dict()
btn = Button(text="{} {}".format(dict['first_name'], dict['last_name']), id=doc.id)
btn.bind(on_release=self.move_to_chat(doc.id))
grid.add_widget(btn)
def move_to_chat(self, *args):
group_id = str(user['localId']) + str(doc.id) # This is where I'm trying to access the user variable but it's getting called on startup due to the above ```btn.bind()``` call.
print(group_id)
MDApp.get_running_app().sm.current = "chat"
The problem I'm having now is that I want to access the user['localId'] value in the __init__ method of another class. As this is run when as soon as the app has loaded the login method hasn't started and therefore there's no user variable.
Error message: NameError: name 'user' is not defined
I am calling a function to validate form in python, but I am getting error :
user = valid_username(username)
NameError: global name 'valid_username' is not defined.
code:
class MainPage(Handler):
def valid_username(self,username):
print USER_RE.match(username)
return USER_RE.match(username)
def render_front(self,username="",password="",error=""):
logins = db.GqlQuery("SELECT * FROM logindb")
self.render("login.html",username=username,password=password,error=error,logins=logins)
def get(self):
self.render_front()
def post(self):
username = self.request.get("userID")
password = self.request.get("pass")
user = valid_username(username)
# pas = isvalid_password(password)
if user and password:
a = logindb(username = username,password=password)
a.put()
self.redirect("/")
else:
error = "we need both username and password"
self.render_front(username,password,error)
valid_username is a class method which means that its name is in the class namespace. But python doesn't look variables up in the class namespace unless you explicitly tell it to do so. When python sees:
user = valid_username(username)
it looks for "valid_username" in the local method scope and then the module scope (confusingly called "global"). Since its not in either, you get the error.
When you define a class method like:
def valid_username(self,username):
the self variable is in the local function scope and refers to the class instance data. You use self to find the method:
user = self.valid_username(username)
Now, python looks up self in the local function scope, realizes its a class instance reference, and continues the lookup by first checking if the name is in the instance variables and then falling back to the class namespace (finally!) where your method is defined.
What I want to do is something like this:
Script1:
import script2
def calc():
instance = script2.User()
instance.user = "me"
script2.vital_function()
Script2:
class User():
user = ""
def vital_function():
# Complex function that uses the User class
So I want to be able to run script2.py inside script1.py with variables set in script1.py. I don't think I have explained myself very clearly. Ask me if something is unclear.
If user must be an object attribute, you can override the init method for the class (its constructor) and pass it the value you need it to store.
class User():
def __init__(self, user):
self.user = user
def vital_function():
...
If, instead, it must be some static value that you share among all the instances of User, either you monkey-patch it as you did, or you define a setter method
class User():
user = ""
#staticmethod
def set_user(user):
User.user = user
but I guess the first way makes more sense.
Are we missing something from your requirements?
Why can't I do this?
from django import forms
from django.forms import widgets
class UserProfileConfig(forms.Form):
def __init__(self,*args,**kwargs):
super (UserProfileConfig,self).__init__(*args,**kwargs)
self.tester = 'asdf'
username = forms.CharField(label='Username',max_length=100,initial=self.tester)
More specifically, why cant the forms.CharField grab the variable tester that I set during construction?
I feel like I am missing something about the way Python handles this sort of thing...
edit :
What I am actually trying to do is this:
class UserProfileConfig(forms.Form):
def __init__(self,request,*args,**kwargs):
super (UserProfileConfig,self).__init__(*args,**kwargs)
self.tester = request.session['some_var']
username = forms.CharField(label='Username',max_length=100,initial=self.tester)
In other words, I need to grab a session variable and then set it to an initial value...
Is there any way to handle this through the __init__ or otherwise?
What you've got doesn't work because your CharField gets created, and pointed to by UserProfileConfig.username when the class is created, not when the instance is created. self.tester doesn't exist until you call __init__ at instance creation time.
You can just do it this way
from django import forms
from django.forms import widgets
class UserProfileConfig(forms.Form):
username = forms.CharField(label='Username',max_length=100,initial=self.tester)
tester = 'asdf'
You could do this:-
class UserProfileConfig(forms.Form):
username = forms.CharField(label='Username',max_length=100)
def view(request):
user_form = UserProfileConfig(initial={'username': request.session['username',})
Which is the generally accepted method, but you can also do this:-
class UserProfileConfig(forms.Form):
def __init__(self,request,*args,**kwargs):
super (UserProfileConfig,self).__init__(*args,**kwargs)
self.fields['username'] = request.session['some_var']
username = forms.CharField(label='Username',max_length=100)
def view(request):
user_form = UserProfileConfig(request=request)