添加类方法

时间:2018-08-18 20:50:33

标签: python python-3.x

我编写了可以正常运行的以下代码:

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'

2 个答案:

答案 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,因为clsMyPoint。 / p>