whenever I try run this code, I receive a TypeError: 'bool' object is not callable. How could I fix this code to make it so that when I try and print bike.blue() I get a boolean value?
class Colour():
def __init__(self):
self.blue = False
def blue(self) -> bool:
return self.blue
bike = Colour()
print(bike.blue())
CodePudding user response:
In your __init__
method, you create an attribute blue
on the instance. This shadows the method blue()
defined on your class, so you can no longer access the method as an attribute of the instance. self.blue()
then is the same as False()
and you can see why that gives you an error.
Name the instance attribute something else, such as _blue
.
CodePudding user response:
When you define the class, self.blue
is a function. But when your __init__
runs, you erase the function, and assign a boolean. After that, obj.blue
returns the boolean, not the function.
It is never a good idea to give a class variable the same name as a member function.