tookas92
tookas92

Reputation: 225

How to move object instance to another class?

Basically I want to have two classes Trades and HistoricalTrades. The second one would be a copy of the first with few more attributes. The Trades instances would be deleted after I get copies on HistoricalTrades

I have solved this by passing attributes manually.

class Trades:
    ...

class HistoricalTrades:
    ...

k = Trades(price=123, amount=10)
h = HistoricalTrades(price=k.price, amount=k.amount, sell_date=k.sell_date)
k.delete()

It kinda works as expected but I feel it is not elegant. Is there any other (better) way to move class instance to other class?

Upvotes: 0

Views: 718

Answers (2)

ShadowRanger
ShadowRanger

Reputation: 155505

For this specific case, assuming no use of __slots__, and that the three attributes used are in fact the sole attributes of Trade, you could get away with a small cheat, changing:

h = HistoricalTrades(price=k.price, amount=k.amount, sell_date=k.sell_date)

to:

h = HistoricalTrades(**vars(k))

vars(k) returns the __dict__ of k itself, which we then unpack with ** into the name/value pairs as the keyword arguments to initialize HistoricalTrades with.

That solution is a little kludgy (as noted, it depends on not using __slots__ and not having any other attributes). Really, the nice way to do this is to define an alternate constructor for HistoricalTrades that does the slog work for you, simplifying use for the caller:

class HistoricalTrades:
    ...
    @classmethod
    def from_trade(cls, trade):
        return cls(price=trade.price, amount=trade.amount, sell_date=trade.sell_date)

Yeah, it's the same code, but it's written once, and every call site can simplify to:

h = HistoricalTrades.from_trade(k)

which is both concise and self-documenting.

Upvotes: 2

Reedinationer
Reedinationer

Reputation: 5774

Inheritance sounds useful here:

class Trades:
    ...

class HistoricalTrades(Trades): # This will make HistoricalTrades inherit characteristics from Trades
    ...

h = HistoricalTrades(price=123, amount=10, sell_date="Some data not provided")

But I think more information would be needed for us to provide you with a more appropriate answer...

Upvotes: 0

Related Questions