In Python, can I create or inherit an object out of another object without losing or overriding previously existing attributes from the older object?

Viewed 36

Say I have a base class called Publication:

class Publication():
    def __init__(self, title='Default', price='Default')
        self.title = title
        self.price = price

    def gettitle(self):
        self.title = input("Please type in a title: ")

    def getprice(self):
        self.price = input("Please type in a price: ")

And a subclass called Book that inherits from Publication:

class Book(Publication):
    def __init__(self, title, author, pages, current_page, price):
        super().__init__(title, price)
        self.author = author
        self.pages = pages
        self.current_page = current_page
    def turnpage(self.current_page):
        self.current_page += 1

Let's say early on in the course of my program, I create an object from the Publication class:

item = Publication()

But later on I have to assign my title and my price:

item.gettitle()

item.getprice()

I input "Lord of the Rings" and 10.99 respectively so now

item.title = "Lord of the Rings" 

and

item.price = 10.99

Now, let's say I have some logic in my program that, depending on the price or if the title matches a string in a list, then we know specifically it is a book (as opposed to something like a magazine or a newspaper) so now I'd like it to be

item = Book()

When I originally created my object from the Publication class, I didn't know it was a Book. But now that I know, is there a way for me to keep the attributes/methods bound to the originally created object while "extending"/"inheriting" the object (not sure if those are the right words) with the newly available attributes from the Book class?

1 Answers
item = Book(title=item.gettitle(), price=item.getprice())

Or you can add a method in Publication that will give you the array which contains all characteristics of class, and in the __init__ function get all needed parameters by array. Another way is to pass item as an argument so __init__ will get all attributes from created object

Related