Python 3.5.1 - 变量返回none

时间:2016-02-16 20:59:19

标签: python python-3.x nonetype

我的问题是关于某些代码是Udacity分配的一部分。以下代码不返回任何值。我假设我没有打电话给#34;标量"从我的"标准化"正常运作功能。行norm = self.scalar(scale)返回类型none。有人可以给我一个指针吗?

代码:

import math 
from decimal import Decimal, getcontext

getcontext().prec = 10

class Vector(object):
    def __init__(self, coordinates):
        try:
            if not coordinates:
                raise ValueError
            self.coordinates = tuple([Decimal(x) for x in coordinates])
            self.dimension = len(self.coordinates)

        except ValueError:
            raise ValueError('The coordinates must be nonempty')

        except TypeError:
            raise TypeError('The coordinates must be an iterable')

    def __eq__(self, v):
        return self.coordinates == v.coordinates
    def scalar(self, c):
        new_coordinates = [Decimal(c)*x for x in self.coordinates]
        #new_coordinates = []
        #n = len(self.coordinates)
        #for i in range(n):
        #    new_coordinates.append(self.coordinates[i] * c)
        #print(Vector(new_coordinates))

    def magnitude(self):
        new_sq = [x**2 for x in self.coordinates]
        new_mag = math.sqrt(sum(new_sq))
        return (new_mag)

    def normalized(self):
        magnitude = self.magnitude()
        scale = 1/magnitude
        print(scale)
        norm = self.scalar(scale)
        #print(type(norm))
        print(norm)
        return (norm)

my_vector = Vector([1,2])  
Vector.normalized(my_vector)

2 个答案:

答案 0 :(得分:5)

Python有这个很酷的小技巧,如果没有指定,它将始终返回None。因此,如果你编写一个函数hello world,它不会返回任何内容,那么你将得到None。

例如:

def hello_world():
  print('hello world')

result = hello_world()
print(result)  # prints nothing cause result==None

您的scalar方法中没有返回语句,因此它将始终返回None。

我的猜测是你想要返回你在标量中创建的对象

def scalar(self, c):
    new_coordinates = [Decimal(c)*x for x in self.coordinates]
    return new_coordinates

或者为了简洁

def scalar(self, c):
    return [Decimal(c)*x for x in self.coordinates]

答案 1 :(得分:0)

问题在于您尝试从scalar获取值,即使它没有返回任何内容。我不完全确定你要回归的是什么,所以你必须自己处理。

一个值得注意的问题是您的方法调用my_vector实例的属性。从技术上讲,这不是问题,但应该改变它。您的代码应如下所示。

my_vector = Vector([1,2])

my_vector.normalized()