繁体   English   中英

在 function 中调用构造函数,在 python 中

[英]Calling the constructor in a function, in python

我写了一个 class,类似于

class tensor:
    n = 1
    def __init__(self, n):
       self.n = n ;
    def prod(t,sca=1):
       newa = tensor(t.n * sca)
       return newa

但是,例如,当我打印 prod( tensor(1),3 ) 时,出现了问题。 这就好比function定义中的构造函数调用不起作用“newa = tensor(tn * sca)”。 请问如何在 function 中调用它?

当调用 class 的方法时,您不会传递 class 的实例。 它是自动通过的。

这就是我认为你正在努力实现的目标。

class tensor:
    def __init__(self, n):
       self.n = n

    def prod(self, sca=1):
       return tensor(self.n * sca)

然后你可以像这样使用它:

t = tensor(23)
t_scaled = t.prod(2)
print('t:', t.n)
print('t_scaled:', t_scaled.n)

prod不需要是实例方法。 它可以是static方法:

class tensor:
    n = 1
    def __init__(self, n):
       self.n = n ;

    @staticmethod
    def prod(t,sca=1):
       newa = tensor(t.n * sca)
       return newa

t1 = tensor(5)
t2 = tensor.prod(t1, 3)

或者它可以是class方法:

class tensor:
    n = 1
    def __init__(self, n):
       self.n = n ;

    @classmethod
    def prod(cls,t,sca=1):
       newa = cls(t.n * sca)
       return newa

t1 = tensor(5)
t2 = tensor.prod(t1, 3)

实际的 class(在本例中为tensor )将作为调用prod的第一个参数传递。 如果您需要能够修改类的 state,Class 方法很有用,在您的示例中您不需要。

Static 和 class 方法对于实现替代的类似构造函数的方法很有用,您的prod似乎是。

顺便说一句,用大写字母命名类是很常见的。 此外,您的 class 定义中的赋值n = 1似乎没有用处。

暂无
暂无

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

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