2

I have spent a good while searching through this website so I hope this question hasn't been asked before - apologises if it has. I'm learning classes for the first time and I'm making a class with multiple users (could be 50+ but for now, I just have 2 in my example). What I'm trying to do is have certain information about users/employees and be able to print them all in one go... in a way that isn't a complete eyesore! This is what I have attempted:

class User:

    def __init__(self, user_id, first, last, address):
        self.user_id = user_id
        self.first = first
        self.last = last
        self.address = address
        self.email = first + '.' + last + '@python.com'

    def all_users(self):
        print()
        print('User ID: {} First Name: {} {} {} {}'.format(self.user_id, self.first, self.last, self.address, self.email))
        print()


user_1 = User(123, 'Kim', 'N', 'London')

user_2 = User(312, 'Chris', 'E', 'Japan')

print(all_users(User))

This is the error message that I am receiving:

print('User ID: {} First Name: {} {} {} {}'.format(self.user_id, self.first, self.last, self.address, self.email))
AttributeError: type object 'User' has no attribute 'user_id'

Thanks in advance for any help or guidance.

4
  • Please post formatted code. Commented Apr 6, 2018 at 18:03
  • User is a class, not an object. You've confused the two in your program. user_1 and user_2 have the attributes; User does not. Commented Apr 6, 2018 at 18:05
  • @Prune well, classes are objects :) But I think fundamentally the OP is under the misapprehension that classes automatically act as containers for instances of themselves. Commented Apr 6, 2018 at 18:12
  • all_users() is a very misleading method name, as it only prints information for one user. Commented Apr 6, 2018 at 18:16

2 Answers 2

3

Sounds like you want the User class to contain a list of all users.

This is called a class variable because it is attached to the class itself, instead of being attached to a particular instance of the class.

Example code:

class User(object):

    users = []

    def __init__(self, first, last):
        self.first = first
        self.last = last

        # now that this instance is fully initialized, add it
        # to the master list of users
        User.users.append(self)

    def __str__(self):
        return '{} {}'.format(self.first, self.last)

    @staticmethod
    def all_users():
        for user in User.users:
            print (user)

user_1 = User('Kim', 'Smith')
user_2 = User('Chris', 'Jones')

User.all_users()
Sign up to request clarification or add additional context in comments.

2 Comments

This is a good alternative to defining a container class or using a list. The class can keep a list of its own instances.
Brilliant John Gordon - that makes sense. I'm still learning in my own time but it is great to have a place like this to come to get help when stuck. Thanks to everyone for their assistance and time.
3

You should probably implement the __str__ or __repr__ special methods, which are designed to print human readable and "official" representations of the class instances, respectively

class User():
    ...

    def __str__(self):
        attrs = ['{}={}'.format(k, repr(v)) for k, v in self.__dict__.items()]
        return '{}({})'.format(self.__class__.__name__, ', '.join(attrs))

Then it would look like this

>>> user = User('123', 'John', 'Doe', 'USA')
>>> print(user)
User(user_id='123', first='John', last='Doe', address='USA', email='[email protected]')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.