在python中返回实例

在python中返回实例,python,class,python-2.7,Python,Class,Python 2.7,通过这种方式,我可以访问cn.c、cn.d和cn.e。我可以使用除self之外的其他东西来返回它,它将是一个结构。我知道在matlab中可以定义函数的结构。我所期望的应该是这样的: class classname(): def func(self,a,b): self.c = a+b self.d = a-b self.e = a*b return self cn = classname() 我知道这不是一个有效的代码,

通过这种方式,我可以访问cn.c、cn.d和cn.e。我可以使用除self之外的其他东西来返回它,它将是一个结构。我知道在matlab中可以定义函数的结构。我所期望的应该是这样的:

class classname():
     def func(self,a,b):
         self.c = a+b
         self.d = a-b
         self.e = a*b
     return self
cn = classname()

我知道这不是一个有效的代码,但只是我想从代码中得到的一个想法。

我想你想要的是:

class classname():
     def func(self,newself,a,b):
         self.c = a+b
         self.d = a-b
         newself.e = a*b
     return self, newself
cn = classname()

创建对象时会自动调用_uinit _u函数。Self将始终引用对象,因此向其添加属性会将其添加到对象,因此,您不需要返回任何内容。

您应该阅读本书以熟悉Python中类的工作方式。您所说的newself是什么意思以及为什么要使用它?newself只是一个包含effirst值的结构:缩进不正确;第二:有方法uu init uuuu像构造函数一样使用;第三:像uu init uuu这样的构造函数不返回值;第四:函数或方法只能返回一个值。语句return self,newself仍然返回一个值-包含两个成员的tuple:self,newself。OOP一开始有点小技巧,但不要放弃。阅读和学习。
class classname:
    def __init__(self, a, b):
        self.c = a+b
        self.d = a-b
        self.e = a*b
cn = classname(12, 34)  # Just random values for 'a' and 'b'. Use whatever you like!
print(cn.c)
>>> 46
print(cn.d)
>>> -22
print(cn.e)
>>> 408