当我尝试运行函数'iswalking()'时出现此错误
我正在尝试学习OOPs概念,到目前为止,这是我创建的...
class Human:
def __init__(self,name,age,gender):
self.name = name
self.age=age
self.gender= gender
def iswalking(self,TOF):
self.TOF = TOF
if TOF:
print("walking")
else:
print("sitting")
def introduce_self(self):
print("my name is ",self.name)
print("my age is ",self.age)
print("my gender is ",self.gender)
h1=Human("Armaan",16,"male")
h1.iswalking=False
h1.introduce_self()
h1.iswalking()
我希望输出:
my name is Armaan
my age is 16
my gender is male
sitting
我能得到什么:
my name is Armaan
my age is 16
my gender is male
Traceback (most recent call last):
File "main.py", line 19, in <module>
h1.iswalking()
TypeError: 'bool' object is not callable
...Program finished with exit code 1
Press ENTER to exit console.
答案 0 :(得分:2)
您已经将一个函数重新分配给一个布尔值,然后尝试以为它仍然是一个函数的方式调用该布尔值。
相反,您需要这样做:
class Human:
def __init__(self,name,age,gender):
self.name = name
self.age=age
self.gender= gender
def is_walking(self):
if self.iswalking:
print("walking")
else:
print("sitting")
def introduce_self(self):
print("my name is ",self.name)
print("my age is ",self.age)
print("my gender is ",self.gender)
h1=Human("Armaan",16,"male")
h1.iswalking=False
h1.introduce_self()
h1.iswalking()
这避免了重新分配功能。
答案 1 :(得分:0)
h1=Human("Armaan",16,"male")
h1.iswalking=False # first
h1.introduce_self()
h1.iswalking() # second
在第一行中,您已将属性iswalking
更改为False
-这是一个布尔值。
在第二行中,您尝试呼叫设置为iswalking
=的False
-因此,您尝试呼叫False
即False()
-这会引发您所看到的错误。
我相信您想这样做:
h1.iswalking(False)
应该打印:
sitting