Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I try to made easy upgradable classes. Idea in following: I have an instance of class "Person", which has to be converted to another class "Worker" by instantiation using object of class "Person". The main conditions:

  1. "Person" is parent class of "Worker"
  2. init functions are differents from each other

Now I wrote below code. But I wondering: if it is possible to change redundant properties declarations at "Worker" class to something more simple, because base class "Person" can be extended any time, and I don't want to write duplicated code.

And what is best practice to achieve same goal?

class Person:
    def __init__(self, row: dict = None):
        if not row:
            row = {}
        self.first_name = row.get('first_name', None)
        self.last_name = row.get('last_name', None)
        # here goes many properties


class Worker(Person):
    def __init__(self, person: Person):
        super().__init__()
        self.position = 'unemployed'
        # below code which I want to make independent from base class properties
        self.first_name = person.first_name
        self.last_name = person.last_name
        # here goes many properties of base class


person_info = {'first_name': 'John', 'last_name': 'Doe'}
person = Person(person_info)
worker = Worker(person)
print(f'{worker.first_name} {worker.last_name} is {worker.position}')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
156 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can do something like:

class Worker(Parent):
    def __init__(self, person: Person):
        vars(self).update(vars(person))
        self.position = 'unemployed'

Seems pointless to call super().__init__().

Note, the above will only work with a non-slotted class.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...