从重写python类inheritan打印的额外空间

2024-09-28 22:20:01 发布

您现在位置:Python中文网/ 问答频道 /正文

代码如下:

class Parent(object):
    def __init__(self, last_name, eye_color):
        self.last_name = last_name
        self.eye_color = eye_color

    def show_info(self):
        print("The last_name -- " + self.last_name)
        print("The eye_color -- " + self.eye_color)

class Child(Parent):
    def __init__(self, last_name, eye_color, num_toys):
        Parent.__init__(self, last_name, eye_color) ##need self here
        self.num_toys = num_toys

    def show_info(self):
        print("The eye_color -- " + self.eye_color)
        print("The eye_color -- " + self.eye_color)
        print("The num_toys -- " , self.num_toys)
flint = Child("Fan", "Black", 0)
print(flint.eye_color)
flint.show_info()

但是当调用flint.show_info()时,这是输出:

Black
The eye_color --    Black
The eye_color -- Black
The num_toys --  0

姓氏的额外空间是从哪里来的? 如果从Child中删除show_信息,多余的空间将消失。我正在使用python 3.5


Tags: thenameselfinfodefshownumflint
1条回答
网友
1楼 · 发布于 2024-09-28 22:20:01

显然,您在该位置有一个文本制表符(即,您按下了制表符而不是空格):

    def show_info(self):
        print("The eye_color  <<<LITERAL TAB CHARACTER>>>" + self.eye_color)
        print("The eye_color   " + self.eye_color)

理想情况下,您应该配置所使用的编辑器,使制表符和空格可见,以便轻松识别和辨别它们

此外,Python的最佳实践和样式指南建议在源代码中不要使用制表符。因为它们在视觉上可能与空格字符(如您的情况)无法区分,并且可能前进到大不相同的制表位值(如8、4或任何其他奇数值)

相关问题 更多 >