我编写了可以正常运行的以下代码:
import math
class Point:
"""Two-Dimensional Point(x, y)"""
def __init__(self, x=0, y=0):
# Initialize the Point instance
self.x = x
self.y = y
def __iter__(self):
yield self.x
yield self.y
def __add__(self, other):
addedx = self.x + other.x
addedy = self.y + other.y
return Point(addedx, addedy)
def __mul__(self, other):
mulx = self.x * other
muly = self.y * other
return Point(mulx, muly)
def __rmul__(self, other):
mulx = self.x * other
muly = self.y * other
return Point(mulx, muly)
@classmethod
def from_tuple(
@property
def magnitude(self):
# """Return the magnitude of vector from (0,0) to self."""
return math.sqrt(self.x ** 2 + self.y ** 2)
def distance(self, self2):
return math.sqrt((self2.x - self.x) ** 2 + (self2.y - self.y) ** 2)
def __str__(self):
return 'Point at ({}, {})'.format(self.x, self.y)
def __repr__(self):
return "Point(x={},y={})".format(self.x, self.y)
我想向Point类添加一个名为from_tuple的@class方法,该方法允许从包含x和y值的元组创建Point实例。我想这样做,所以需要元组输入。我不知道该如何做这样的语法。以下是预期的输出:
location = 2, 3
print(location)
(2, 3)
point = Point.from_tuple(location)
print(point)
Point(x=2, y=3)
point = Point.from_tuple()
Traceback (most recent call last):
[...]
TypeError: from_tuple() missing 1 required positional argument: 'coords'
答案 0 :(得分:3)
就是
import {UPDATE_USER, CREATE_USER,CREATE_SKILL,CHECK_USER} from '../actions/index';
const DEFAULT_STATE =
{
createdAt:"",
name:"",
email:"",
password:"",
skill:"",
goal:"",
step1:"",
step2:"",
step3:"",
step4:"",
step5:"",
posts:[],
completed:0
}
export default function(state = DEFAULT_STATE, action) {
if (action.error) {
action.type = 'HANDLE_ERROR'; // change the type
}
switch (action.type) {
case UPDATE_USER:
return Object.assign({},state,{
completed:action.payload.completed
})
答案 1 :(得分:3)
classmethod
与实例方法非常相似,除了:
传统上,您将参数命名为cls
。所以:
@classmethod
def from_tuple(cls, tup):
x, y = tup
return cls(x, y)
您可能想知道为什么这里完全需要cls
。毕竟,您难道不能只写成staticmethod
吗?
@staticmethod
def from_tuple(tup):
x, y = tup
return Point(x, y)
是的,您可以-但是在继承中不能很好地发挥作用。如果我创建Point
的子类并调用MyPoint.from_tuple(2, 3)
,则希望得到一个MyPoint
而不是一个Point
。通过使用classmethod
并构造cls
的实例而不是对Point
进行硬编码,我得到了MyPoint
,因为cls
是MyPoint
。 / p>