Reputation: 11
I was wondering if anyone could help me with something. If I have a class that has an attribute is there a way to automatically make an object of that class return that attribute whenever it is called
class Constant():
def __init__(self, value):
self.__value = value
PI = Constant(3.14)
Is there any way for it to return 3.14 (as an actual float not a string) without explicitly defining the __float__
method and calling float(PI)
. I want to be able to just say something along the lines of print(PI*2)
and to get 6.28
as my output
EDIT:
I found what I wanted, by using the __new__
method i can change the return value from an instance to whatever I want.
2nd EDIT: turns out that didn't work.
Upvotes: 1
Views: 2765
Reputation: 71560
Try subclassing float
:
class Constant(float):
def __init__(self, value):
self.__value = value
PI = Constant(3.14)
print(PI*2)
Output:
6.28
Upvotes: 4
Reputation: 1766
Try this for accessing a private variable
class Constant():
def __init__(self, value):
self.__value = value
PI = Constant(3.14)
print(PI._Constant__value*2)
6.28
Upvotes: 1