Reputation: 308
I know about the nature of python object names being nothing but "labels" that can be attached to any object and that variables are always passed by reference. But what if I need a different behavior?
To illustrate this, I made a Short example:
class car:
def __init__(self, brand):
self.brand = brand
subaru = car("subaru")
toyota = car("toyota")
current_car = subaru
current_brand = current_car.brand
print (current_brand)
current_car = toyota
print (current_brand)
The Output I get is:
subaru
subaru
This doesn't surprise me. However in the project I'm working on right now, I would like to express a selection by making current_car the selected car. Also I would like the object current_brand to always hold the brand of the current car without explicitly doing:
current_brand = current_car.brand
every time I switch the current car. I thought about using a property decorator for this, but I am not shure, that that's the right way. Is there a pythonic way to do this or am I thinking in the wrong direction all-together?
Upvotes: 1
Views: 61
Reputation: 308
Well, it turns out, that I had a weird knot in my brain, which was keeping me from understanding even the simplest basics of programming. For the unlikely chance someone else goes down the same dead end road of thinking (and happens to find this post) here is what I meant to do:
class car:
def __init__(self, brand):
self.brand = brand
subaru = car("subaru")
toyota = car("toyota")
current_car = subaru
def current_brand():
return current_car.brand
print (current_brand())
current_car = toyota
print (current_brand())
I didn't get that all I tried to do was to have a function that gives me the current_car's brand.
Well, maybe I should take a break and go outside for a while...
Upvotes: 1
Reputation: 149085
I can only think of a __repr__
trick: when you display, print or convert an object to a string, you use its __repr__
method to do the conversion. Here, you could try:
class CurrentBrand:
def __repr__(self):
return current_car.brand
current_brand = CurrentBrand()
Now if you do:
subaru = car("subaru")
toyota = car("toyota")
current_car = subaru
print (current_brand)
current_car = toyota
print (current_brand)
The output will be as expected:
subaru
toyota
The limits of the trick are that any direct assignement to current_car
will break the magic, and that it is not a string...
Upvotes: 1