0 Replies - 303 Views - Last Post: 11 January 2022 - 10:22 AM Rate Topic: -----

#1 Pogaca   User is offline

  • D.I.C Head

Reputation: 10
  • View blog
  • Posts: 202
  • Joined: 24-August 13

Adding class attributes dynamically

Posted 11 January 2022 - 10:22 AM

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.

Is This A Good Question/Topic? 0
  • +

Page 1 of 1