I’m attempting to use the @property decorator on a specific instance of a class in Python and not on the class itself, but I’m encountering issues. Here is what I typically do:
class MyNet:
def __init__(self):
self.weight = 1 # Example value
@property
def quantized_weight(self):
return quantize(self.weight)
However, when I try to apply a property to just one instance of the MyNet
class, it doesn’t behave as expected:
class MyNet:
def __init__(self):
self.weight = 1 # Example value
net = MyNet()
def quantized_weight(self):
return quantize(self.weight)
net.quantized_weight = property(quantized_weight)
After executing the above code, when I attempt to access net.quantized_weight
, instead of returning the result of the quantize function, it gives me <property at 0x7fdcf422bd30>
.
Can someone explain why this occurs and how I can correct it so that the property works on an instance level as intended?
I read the documents on Python property: https://docs.python.org/3/library/functions.html#property
It shows that property should be used in Class.
I find this: Python property returning property object
So, how can i apply a function as property on an instance? I don’t want to break the other instance.
OfferOverflow is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
4