如何在 python 中创建打印功能

How to create a print function in python

我尝试编写一种新型的打印功能,我希望以程序的方式打印出文本,所以我这样写:

def print(text):
    for t in text:
        sys.stdout.write(t)
        sys.stdout.flush()
        time.sleep(0.1) 
print('Monkey')
#program stamp  Monkey  letter by letter with delay of 0.1 sec

但是,如果不是 'Monkey',我把它放在里面 ('text', object.param, 'text') 它不起作用;

一个例子是:

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

Monkey.name = 'George'

def print(text):
    for t in text:
        sys.stdout.write(t)
        sys.stdout.flush()
        time.sleep(0.1)
print('Monkey', Monkey.name, 'is funny')

#TypeError: print() takes 1 positional argument but 2 were given

我如何对这个新打印进行编程以获得与普通打印相同的功能,但有额外的延迟可能性?

改变

def print(text)

对此:

def print(*texts)

它接受多个参数。

然后这样做:

def print(*texts):
    for text in texts:
        for t in text:
           sys.stdout.write(t)
           sys.stdout.flush()
           time.sleep(0.1) 

编辑

如果你也想打印出int,你可以把int转换成str:

def print(*texts):
    for text in texts:
        text = str(text) # Notice!! I added this line
        for t in text:
           sys.stdout.write(t)
           sys.stdout.flush()
           time.sleep(0.1) 

您可以在参数文本前添加星号。

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

Monkey.name = 'George'

def print(*text):
    for t in text:
        sys.stdout.write(t)
        sys.stdout.flush()
        time.sleep(0.1)
print('Monkey', Monkey.name, 'is funny')