-1

So I'm a beginner with python, this is like my 3rd day learning it so I'm sorry if this is too obvious for you.

I'm creating a class called Users() that takes first_name, last_name, user_name and password as arguments and I wan't to assign their values to self with a for loop

I'm first defining __init_ with self and the parameters, and then a for loop that it's like this:

  def __init__(self, name, lastName, user, password):
   for i in self:
    self.i = i

so I don't have to do this

def __init__(self, name, lastName, user, password):
 self.name     = name
 self.lastName = lastName
 self.user     = user
 self.password = password

But it's not working

I get this error: for i in self: TypeError: 'Users' object is not iterable

How can I make this work?

  • 3
    Use the second form, and don't try to use "magic". You'll appreciate it later. – Jonathon Reinhart Jun 01 '19 at 02:24
  • Possible duplicate of [Automatically initialize instance variables?](https://stackoverflow.com/questions/1389180/automatically-initialize-instance-variables) – wjandrea Jun 01 '19 at 02:34

1 Answers1

1

As a beginner (and even more as an expert), you should do things in the simplest way. Use the second form:

def __init__(self, name, lastName, user, password):
    self.name     = name
    self.lastName = lastName
    self.user     = user
    self.password = password

That said, Python3.7 introduced dataclasses. So if you're in a hurry to define a class you could do it this way (untested, might have a typo):

import dataclasses


@dataclasses.dataclass()
class User():
    first_name: str
    last_name: str
    username: str
    password: str

u = User('Bob', 'Marley', 'bm', 'bob')

print(u)
Ben
  • 5,952
  • 4
  • 33
  • 44
  • Thanks! Exactly what I was looking for, it seemed redundant to write 3 times the name of the parameter just to initialize the attribute. I have a question, do you know why they say that this method is only for classes that stores data? – Alejandro Rosales Jun 01 '19 at 02:58
  • 1
    @AlejandroRosales , some classes don't just hold data - they're abstract or do weird things (see Pandas DataFrames or Django Models). It's probably better not to use dataclasses for something like that. But *most* classes just hold data and have some methods (especially as a beginner). Those are good candidates for dataclasses. If in doubt, read the docs. – Ben Jun 01 '19 at 03:06