Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
151 views
in Technique[技术] by (71.8m points)

python - What is right way to create upgradable classes

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}')

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...