新人求教,拜托了
class Dog:def __init__(self,name):
self.name=name
self.__age=None
def set_age(self,age):
if not isinstance(age,int):
print("请输入的年龄必须是数字!")
return False
if age <=0:
print("年龄必须大于零!")
return False
self.__age=age
def play(self):
print("今年"+self.__age)
dog=Dog("旺财")
dog.set_age('hello')
dog.set_age(-20)
dog.set_age(3)
dog.play()
SyntaxError: invalid syntax
>>>
>>>
>>>
================================================================== RESTART: C:/Users/owo/AppData/Local/Programs/Python/Python39/Dog.py ==================================================================
请输入的年龄必须是数字!
年龄必须大于零!
Traceback (most recent call last):
File "C:line 19, in <module>
dog.play()
File "C: line 14, in play
print("今年"+self.__age)
TypeError: can only concatenate str (not "int") to str
__age 变量是整型,不能与字符串进行 + 号运算,因为 +号对字符串来说是拼接,对整型来说是加法运算导致报错
参考代码,play 的函数 print 函数参数内容改改就行 :
print("今年",self.__age,'岁')
页:
[1]