Quantcast
Viewing latest article 48
Browse Latest Browse All 51036

Adding class attributes dynamically

So, I am pretty new to Python and what interests me at the moment is, how can I put a list inside class constructor and use that to create attributes in class?

Let me give you example of what I want:

class Student:
    '''This is a Student class'''

    def __init__(self, first_name, last_name, gender, major, age, ID):
        self.first_name = first_name
        self.last_name = last_name
        self.gender = gender
        self.major = major
        self.age = age
        self.ID = ID

    def student_info(self):
        student_data = [
            self.first_name,
            self.last_name,
            self.gender,
            self.major,
            self.age,
            self.ID
        ]
        return student_data

    def student_id(self):
        return self.ID

class LibraryCard:

    def __init__(self, student_data):
        for data in student_data:
            exec(f"self.{data} = '{data}")

student1 = Student('Alex', 'Arsic', 'male', 'IT', 29, '234123')
card1 = LibraryCard(student1.student_info())
print(card1.card_data())




I mean, all of this is just for learning, doesn't have any real purpose for some work.

Viewing latest article 48
Browse Latest Browse All 51036

Trending Articles