Python 你能在一行上调用多个方法吗?

Python 你能在一行上调用多个方法吗?,python,python-2.7,python-3.x,Python,Python 2.7,Python 3.x,例如,我想: texta = text.lower() textacopy1 = texta.replace(string.punctuation, ' ') textacopy2 = textacopy1.split(' ') 有没有一种更干净的方法可以做到这一点,而不必分配多个变量 如果2.7和3.x之间有差异,我更喜欢3.x的解释 result = text.lower().replace(string.punctuation, ' ').split(' ') 伟大的python带来了

例如,我想:

texta = text.lower()
textacopy1 = texta.replace(string.punctuation, ' ')
textacopy2 = textacopy1.split(' ')
有没有一种更干净的方法可以做到这一点,而不必分配多个变量

如果2.7和3.x之间有差异,我更喜欢3.x的解释

result = text.lower().replace(string.punctuation, ' ').split(' ')
伟大的python带来了巨大的责任:不要滥用这个特性

编码的规范最大行长为80个字符, 拆分方法链的标准方法是在点处开始新行:

result = text.lower().replace(string.punctuation, ' ')
        .split(' ')

您可以使用一个变量,而不必使用可能导致混淆的多个变量。代码也会更干净。你也可以在一行中完成

text = text.lower()
text = text.replace(string.punctuation, ' ')
text = text.split(' ')
你也可以在一行中完成

text = text.lower().replace(string.punctuation, ' ').split(' ')

对于正则表达式,它甚至更干净

    In [132]: split_str = re.compile(r'[{} ]+'.format(string.punctuation))

    In [133]: split_str.split("You can do it with one variable you don't have to use multiple variable which can cause confusion. Also code will be much cleaner. You can do it in one line also.")
    Out[133]: 
    ['You',
     'can',
     'do',
     'it',
.....
     'in',
     'one',split_string = 
     'line',
     'also',
     '']

问题是-它适用于不可变对象,例如字符串,因为每次调用都返回一个新对象

'Hello'.lower().replace('ell', '') # 'ho'
但它可能不适用于可变对象,如列表、dict、用户定义对象,因为这些方法通常不返回任何值

{1: 'chicken', 2: 'duck'}.update({3: 'goose'}) # None
#                         dict gets lost here
所以我想出了一个解决办法

获取可变对象>执行方法>返回对象

a = take([1, 2, 3]).append(4).extend([5, 6]).unwrap()
# a = [1, 2, 3, 4, 5, 6]

b = take({1: 'chicken', 2: 'duck'}).update({3: 'goose'}).update({4: 'moose'}).unwrap()
# b = {1: 'chicken', 2: 'duck', 3: 'goose', 4: 'moose'}
代码:


Github代表:

与dot的接触很好-顺便说一句,据我所知,
replace(string.标点符号),
可能不符合您的要求。您必须为
标点符号中包含的所有单个字符调用它。
@mkrieger1是的,这是我用循环修复的问题。
class take:
    class mockmeth:
        def __init__(self, name, taken):
            self.name = name
            self.bounded = getattr(taken.obj, name)
            self.taken = taken

        def __call__(self, *args, **kwargs):
            self.bounded(*args, **kwargs)
            return self.taken

    def __init__(self, obj):
        self.obj = obj

    def __getattr__(self, name):
        return self.mockmeth(name, self)

    def unwrap(self):
        return self.obj