简体   繁体   English

在Python中同时使用字符串和线程中的join()

[英]Using join() from both string and threading at the same time in Python

In one of my script, I used join() method from both string and threading of python. 在我的脚本之一中,我从python的字符串和线程中都使用了join()方法。 I tried to use import ... as to rename the module name like this: 我试图使用import ... as重命名模块名称,如下所示:

import str.join as sjoin
import threading.Thread.join as tjoin

But I always cannot get the string join imported properly. 但是我总是无法正确导入字符串连接。 I check the official doc, both join() class paths should be right. 我检查了官方文档,两个join()类路径都应该正确。 What should I do to use the two join at the same time? 我应该怎么做才能同时使用两个联接?

EDIT 编辑

Initially I didn't import str.join(). 最初,我没有导入str.join()。 But since I got type error, I thought I should rename the join(). 但是由于出现类型错误,我认为我应该重命名join()。 But later, I realized that I passed wrong thing into the str.join(), this is the real reason why I got type error. 但是后来,我意识到我将错误的内容传递给了str.join(),这是我遇到类型错误的真正原因。 My fault! 我的错!

str.join() is a method, used on an instance of a string, so, for example: str.join()是一种用于字符串实例的方法,因此,例如:

>>> ", ".join([1, 2, 3])
1, 2, 3

No need to import anything. 无需导入任何东西。 I use a string literal here as an example, but of course, any string can be used. 我在这里使用字符串文字作为示例,但是当然可以使用任何字符串。 This is then the 'glue' that joins the strings from the iterable (passed to the method) together. 这就是将来自可迭代(传递给方法)的字符串连接在一起的“胶水”。

This is also true of threading.Thread.join() - you should make an instance of the Thread class and use the join() method on that instance. 对于threading.Thread.join()也是如此,您应该创建Thread类的实例,并在该实例上使用join()方法。

Note that due to the way Python works, you can access these methods directly from the class, then pass the instance as the first argument, however, this is generally a very bad idea, as it's harder to read and more effort than calling them normally. 请注意,由于Python的工作方式,您可以直接从类中访问这些方法,然后将实例作为第一个参数传递,但是,这通常是一个非常糟糕的主意,因为与通常调用它们相比,它更难阅读且更费力。

str is a builtin, not a module, so you can't import from it. str是内置的,不是模块,因此无法从中导入。 You could however do: 但是,您可以这样做:

sjoin = str.join
import threading.Thread.join as tjoin

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM