Kevin
Kevin

Reputation: 81

Merging inherited class's variable

I'm trying to merge a dictionary of a subclass with class inheritance

class Person(object):
    nametag = {
        "name": "Bob",
        "occupation": "Nobody"
    }

class Teacher(Person):
    nametag = {
        "occupation": "Professor",
        "Subject": "Python"
    }

    def __init__(self):
        nametag = dict(Person.nametag.items() + self.nametag.items())

Ultimately I need:

Teacher().nametag["name"] == "bob"
Teacher().nametag["occupation"] == "Professor"
Teacher().nametag["subject"] == "Python"

Side note, Teacher.nametag and Person.nametag are going to be very large dictionaries, is dict(d2.keys() + d1.keys()) the best way to do it?

Upvotes: 0

Views: 2082

Answers (2)

jonrsharpe
jonrsharpe

Reputation: 122024

Presumably, each instance of your various classes is going to have a different nametag. Therefore, the best implementation is not the class attribute dictionary you currently have, but instance attributes:

class Person(object):
    def __init__(self, name, occupation):
        self.name = name
        self.occupation = occupation

class Teacher(Person):
    def __init__(self, name, occupation, subject):
        super().__init__(name, occupation)
        self.subject = subject

bob = Teacher("Bob", "Professor", "Python")
bob.name == "Bob"

If you actually need the nametag, you could implement it as:

class Person(object):

    def __init__(self, name, occupation):
        self.name = name
        self.occupation = occupation

    @property
    def nametag(self):
        return {"name": self.name,
                "occupation": self.occupation}

class Teacher(Person):

    def __init__(self, name, occupation, subject):
        super().__init__(name, occupation)
        self.subject = subject

    @property
    def nametag(self):
        tag = super().nametag
        tag["subject"] = self.subject
        return tag

bob = Teacher("Bob", "Professor", "Python")
bob.nametag["name"] == "Bob"

As a side note,

dict(d2.keys() + d1.keys())

Will give you an error. To combine two dictionaries, do:

d1.update(d2)

Upvotes: 3

thebjorn
thebjorn

Reputation: 27311

If the nametags need to be properties of Person and Teacher, then pulling them out as separate classes that inherit from each other will work (think database foreign keys):

class PersonNametag(object):
    name = 'Bob'
    occupation = 'Nobody'


class TeacherNametag(PersonNametag):
    occupation = 'Professor'
    Subject = 'Python'


class Person(object):
    def __init__(self):
        self.nametag = PersonNametag()


class Teacher(Person):
    def __init__(self):
        self.nametag = TeacherNametag()

Upvotes: 0

Related Questions