2024-04-29 03:01:21 发布
网友
我有以下课程:
user = User( first_name=first_name, last_name=last_name, email=email, age=age, )
我知道在JS ES6中你可以写这个
const foo = {x, y, z}
而不是:
const foo = { x: x, y: y, z: z, }
我想知道Python是否也有一个简单的解决方案,可以在每次都不重复名称的情况下编写这个简短的代码。你知道吗
在python中,只需使用__init__。这将允许您创建新类并传入参数。它像JavaScript一样速记吗?有点,但不是真的。当然,创建init函数并传入值比新建类和设置每个属性更便宜/更快
__init__
class Complex: def __init__(self, realpart, imagpart): self.r = realpart self.i = imagpart
然后你可以这样做:
x = Complex(3.0, -4.5) x.r, x.i (3.0, -4.5)
https://docs.python.org/3/tutorial/classes.html
在JavaScript中,运行下面的代码并不一定是类的新代码,还有一点更复杂。但是,如果已经定义了x、y和z,那么您就可以这样做。你知道吗
x
y
z
const x = 'x'; const y = 'y'; const z = 'z'; console.log( { x, y, z} ); // OR const obj = {x: 'x', y: 'y', z: 'z'}; console.log( {...obj }); // OR console.log({x: 'x', y: 'y', z: 'z'});
在python中,只需使用
__init__
。这将允许您创建新类并传入参数。它像JavaScript一样速记吗?有点,但不是真的。当然,创建init函数并传入值比新建类和设置每个属性更便宜/更快然后你可以这样做:
https://docs.python.org/3/tutorial/classes.html
在JavaScript中,运行下面的代码并不一定是类的新代码,还有一点更复杂。但是,如果已经定义了
x
、y
和z
,那么您就可以这样做。你知道吗const x = 'x'; const y = 'y'; const z = 'z'; console.log( { x, y, z} ); // OR const obj = {x: 'x', y: 'y', z: 'z'}; console.log( {...obj }); // OR console.log({x: 'x', y: 'y', z: 'z'});
;相关问题 更多 >
编程相关推荐