Python 更改对象的属性并在一行中返回该对象

Python 更改对象的属性并在一行中返回该对象,python,Python,是否可以重写此代码: def function(obj): obj.attrib = 8 return obj 那么属性集和返回行只出现在一行中?比如: def function(obj): return obj.attrib = 8 # of course, this does not work 您可以这样做: def function(obj): return setattr(obj, 'attrib', 8) or obj 这是因为内置函数不返回任何值

是否可以重写此代码:

def function(obj):
    obj.attrib = 8
    return obj
那么属性集和返回行只出现在一行中?比如:

def function(obj):
    return obj.attrib = 8 # of course, this does not work
您可以这样做:

def function(obj):
    return setattr(obj, 'attrib', 8) or obj
这是因为内置函数不返回任何值。

您可以这样做:

def function(obj):
    return setattr(obj, 'attrib', 8) or obj

这是因为内置函数不返回任何对象。

您不需要返回对象,您在参数中传递给函数的对象将设置
attrib
,您可以直接从调用方代码引用它

class A:

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

def function(obj):
    obj.attrib = 8

obj = A(5)
#This line prints 5
print(obj.attrib)
#5
function(obj)
#This line prints 8
print(obj.attrib)
#8
或者更好的方法可能是:

class A:

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

    def function(self, attrib):
        self.attrib = attrib

obj = A(5)
print(obj.attrib)
#5
obj.function(8)
print(obj.attrib)
#8

您不需要返回对象,在参数中传递给函数的对象将设置
attrib
,您可以直接从调用方代码引用它

class A:

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

def function(obj):
    obj.attrib = 8

obj = A(5)
#This line prints 5
print(obj.attrib)
#5
function(obj)
#This line prints 8
print(obj.attrib)
#8
或者更好的方法可能是:

class A:

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

    def function(self, attrib):
        self.attrib = attrib

obj = A(5)
print(obj.attrib)
#5
obj.function(8)
print(obj.attrib)
#8


好吧,Python仍然有
so
obj.attrib=8;return obj
应该这样做。但我猜,你是在找一个把戏。我认为没有。Python不是编写高尔夫代码的最佳语言。把它放在一行而不是两行中没有好处。你甚至不需要返回任何东西,检查我下面的答案!好吧,Python仍然有
so
obj.attrib=8;return obj
应该这样做。但我猜,你是在找一个把戏。我认为没有。Python不是编写高尔夫代码的最佳语言。把它放在一行而不是两行中没有好处。你甚至不需要返回任何东西,检查我下面的答案!将来阅读此文章的人将不得不对
setattr
可能返回的内容感到困惑,因为对任何有理智的人来说,这读作“返回
setattr
返回的内容或返回到
obj
”……我在发布后几分钟更改了答案,以包含对
setattr
函数的引用。是的,这是对Python的滥用,是一种黑客行为,是一种利用副作用的行为,但这是对给定问题的回答。我的意思是,如果你在生产代码中使用它,任何在你后面的人都会对此感到困惑。因此,您需要包含一个链接到此答案或文档的注释行,以使代码真正易懂,此时您又有两行…;-)我同意。如果问题是“我应该在一行中这样做吗?”我会回答“不”。:)将来读到这篇文章的人都会对
setattr
可能返回的内容感到困惑,因为对任何明智的人来说,这是“返回
setattr
返回的内容或返回到
obj
”…我在发布答案几分钟后更改了答案,添加了对
setattr
函数的引用。是的,这是对Python的滥用,是一种黑客行为,是一种利用副作用的行为,但这是对给定问题的回答。我的意思是,如果你在生产代码中使用它,任何在你后面的人都会对此感到困惑。因此,您需要包含一个链接到此答案或文档的注释行,以使代码真正易懂,此时您又有两行…;-)我同意。如果问题是“我应该这样做吗?”我会回答“否”:)虽然这代表了最佳实践,但它不能回答问题。它避免了从
函数
返回
的需要,从而使问题的意图无效!虽然这代表了最佳实践,但它并没有回答问题。它避免了从
函数
返回
的需要,从而使问题的意图无效!