Hey there I'm new to python and try to program a simple login module which salts a password
When I use this class I get the following error:
TypeError: salting() missing 1 required positional argument: 'password'
class Login():
def salting(self, username, password):
self.password = password
self.username = username
print(self.username + self.password)
Login.salting("user1","pw1")
My Only Solutions were to use Login.salting("","user1","pw1") with an empty string for self or calling self as username end reuse it like this, but I think that I ran in an error, can someone help me :D
But when I compare that with my previous code which was like this (I learned that with this code) - the error doesn't appear...
class car():
name = "BMW"
color = "red"
def redesign(self, color):
self.color = color
c = car()
print(c.name)
print(c.color)
c.redesign("blue")
print(c.color)
THANKS
salting is an object method, not a class method. Each object has its own username and password attributes. You need to create a Login object, and then call the method on that.
s = Login()
s.salting("user1", "pw2")
This is analogous to using c = car() in the second block of code.
Related
I am writing a class that stores credentials. The credential can have a password_getter attribute which stores a lambda that will get the password on-demand. This getter needs access to self.username in order to function. How can this be accomplished? Consider the following setup:
class Credential:
"""Defines one username and password combination, and how to get them."""
def __init__(self, username: str, password_getter: callable):
self.username = username
self._password_getter = password_getter
#property
def password(self) -> str:
self.password = self._password_getter()
return self.password
Then we define a new credential:
cred = Credential(
username="test",
password_getter=lambda self: self.username+"_pass",
)
assert cred.password == "test_pass"
The above is non-functional due to self not existing during definition, but it suggests what I'm trying to do: Access the current value of cred.username from inside the lambda.
For some context as to why this is happening; the function in production actually goes out to a password vault api and requests the password for the given username.
The Callable you pass in has no intrinsic connection to the instance, so your two options are to give it implicit or explicit access. Implicit would rely on simple closures:
cred = Credential(
username="test",
password_getter=lambda: cred.username + "_pass",
)
The problem here is if you reassign cred later and it refers to the wrong instance when trying to get the password.
The explicit alternative is:
cred = Credential(
username="test",
password_getter=lambda instance: instance.username + "_pass",
)
...
#property
def password(self) -> str:
self.password = self._password_getter(self)
The class explicitly passes itself to the password getter. So it should be typed as Callable[[Credentials], str], i.e. something that receives an instance of the class as argument and is expected to return a string.
This question already has answers here:
What is the purpose of the `self` parameter? Why is it needed?
(26 answers)
Closed 4 months ago.
I am trying to write a class that allows users to register on a platform with a username, but checks that this username does not exist in the database.
I have this code:
class Freelancer:
"""Leaving this blank for now while I explore the functionality """
number_of_sales = 0
available_niches = ["Graphic design", "Art", "Data Analysis", "Music", "Business", "Writing and Translations"]
usernames = []
def __init__(self, username):
self.username = _check_username(username)
def _check_username(self, username):
if self.username in Freelancer.usernames:
print("This username already exist on our database, consider choosing another one")
else:
self.username = username
Freelancer.usernames.append(self.username)
print("You have successfully setup a username on our platform")
which I tested like so:
David = Freelancer("dave23")
But I got an exception: NameError: name '_check_username' is not defined. What is wrong with the code? How can I call a private method from __init__?
You missed self before calling private method.
def __init__(self, username):
self.username = self._check_username(username)
If it is still gives error like: 'Freelancer' object has no attribute 'username'
define username variable
First of all, __init__ is not the constructor.
Note that __init__(self) already has the object (self), so it was already constructed before calling __init__. (The real constructor in Python is __new__).
Python does not have private methods, no matter how many underscores you add.
This should work:
def __init__(self, username):
self.username = self.check_username(username)
def check_username(self, username):
...
You could add the leading underscore to indicate that the method is for internal use only.
There is however another mistake in the code. It should be:
def _check_username(self, username):
if self.username in self.usernames: # <-----
print("This username already exist on our database, consider choosing another one")
else:
self.usernames.append(self.username) # <-----
return username
You are manipulating the class. That means that if the class is instantiated again usernames is not empty.
I have the following method:
def _loginEventHandler(cmdID, *args):
if cmdID == Login.LOGIN_LOGED:
user = args[0]
print("User",user.userTypeID,"logged in")
that method is called like this from a different module:
user = User(nUserSelected)
_loginEventHandler(Login.LOGIN_LOGED,user)
the interpreter throws an AttributeError:
file "/main.py", line 79, in _loginEventHandler
print("User",user.userTypeID,"logged in")
AttributeError: 'tuple' object has no attribute 'userTypeID'
The question is what is the proper way of taking arguments from *args (specially if they are custom types like with "User") and why is it taking a tuple from args[0]
You didn't include self in the definition of the method. The first argument passed to a method is always the instance itself. That means that in your method, cmdID is taking the value of the instance, and the first element of args is actually the value of Login.LOGIN_LOGED, which is presumably a tuple.
So I tried to come up with a minimal version of the User class and a Login Enum. But I don't see any problems here. The output seems okay
from enum import Enum
class Login(Enum):
LOGIN_LOGED = 1
class User:
def __init__(self, userTypeID):
self.userTypeID = userTypeID
user = User(1)
_loginEventHandler(Login.LOGIN_LOGED, user)
which gives
('User', 1, 'logged in')
When I run the following code
class Userx(ndb.Model):
username = ndb.StringProperty()
password = ndb.StringProperty()
date = ndb.DateTimeProperty(auto_now_add=True)
class adduser(BaseHandler):
def get(self):
user=self.request.get("email")
o=Userx(parent=ndb.Key("users","key"),password="123",username=user)
o.put()
I get the error message
o=Userx(parent=ndb.Key("users","key"),password="123",username=user)
NameError: name 'user' is not defined
I don't see anything wrong with that Code Sample, maybe the problem is caused by another part? Indirectly maybe? For example, the following code, which is similar to yours, runs without any problem.
class myc1:
def __init__(self,y=0,q=1,t="Spam Eggs"):
print y,q,t
class myc2:
def get(self):
name1 = "Sweeney Todd"
myobj1 = myc1(q=5,t=name1)
myobj2 = myc2()
myobj2.get()
outputs 0 5 Sweeney Todd
Can you post more of your code?
(p.s I cannot write this as a comment since I don't have sufficient privilege)
I have a UserModel class that will essentially do everything like login and update things.
I'm trying to pass the instance of itself (the full class) as an argument to another function of another class.
For example: (obviously not the code, but you get the idea)
from Car import CarFactory
class UserModel:
def __init__(self,username):
self.username = username
def settings(self,colour,age,height):
return {'colour':colour,'age':age,'height':height}
def updateCar(self,car_id):
c = CarFactory(car_id, <<this UserModel instance>>)
So, as you can see from the very last line above I would like to pass an instance of UserModel to the CarData class, so when within the CarData class I can access the UserModel.settings(), however, I am unsure of the syntax. I could of course just do:
c = CarFactory(car_id,self.settings)
Any help would be grateful appreciated.
Thanks
c = CarFactory(car_id, self)
doesnt work?
on a side note it would be self.settings() not self.settings ... unless you define settings to be a property