Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在方法中添加打印?_Python_Python 3.x_Python 2.7 - Fatal编程技术网

Python 在方法中添加打印?

Python 在方法中添加打印?,python,python-3.x,python-2.7,Python,Python 3.x,Python 2.7,我们可以在类的方法中打印吗?PEP8 我知道最好还是回去。但是我必须把一个大的python文件转换成一个类 class Test: def __init__(self,name): self.name = name self.r = str def tester(self): print('hello') print(self.name) r = Test('pascal') r.tester() 直接回答你的

我们可以在类的方法中打印吗?PEP8
我知道最好还是回去。但是我必须把一个大的python文件转换成一个类

class Test:
    def __init__(self,name):
        self.name = name
        self.r = str

    def tester(self):
        print('hello')
        print(self.name)

r = Test('pascal')
r.tester()

直接回答你的问题,是的。您可以在类中放置print语句。同样正确的是,最好使用return语句,以便更符合可移植性和可重用性

然而,我将在这里做一个假设,您实际上在寻找一种返回类状态的字符串表示的方法

这就是函数的作用

在你的情况下,你会

class Test():
    def __init__(self, name):
        self.name = name
        #self.r = str <-I don't know where "str" is coming from

    def __str__(self):
        return "Hello {0}".format(self.name)
然后打印出来

print(r)
得到

Hello pascal
>>>

你目前遇到了什么问题?我不明白你的问题,你不能运行代码并找出答案吗?我知道最好是返回。-正确,我必须把一个大文件变成一个类。我想知道这个惯例是否允许在类方法中添加打印,或者我们应该完全取消它。而是使用一个返回,然后打印显示。这个文件真的很大,用转录的方法打印东西是完全合理的。
Hello pascal
>>>