【问题标题】:Python 3.5.1 - variable returns nonePython 3.5.1 - 变量不返回
【发布时间】:2016-02-16 20:59:18
【问题描述】:

我的问题是关于 Udacity 作业中的一些代码。以下代码不返回任何值。我假设我没有从我的“标准化”函数中正确调用“标量”函数。 norm = self.scalar(scale) 行返回无类型。谁能给我指点一下?

代码:

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)

【问题讨论】:

  • 嗯,标量方法中有return语句吗?
  • 这是合法的进口方式吗?这可能不是您的问题的根源,但不应该是:import math 在一行上,from decimal import Decimal, getcontext 在另一行上?
  • @Igor 我认为这是一个复制粘贴问题,它可能应该是import math; from decimal import .. 其中; 是换行符
  • @NickHumrich 这是因为 Blckknght 试图修复导致代码的顶部和底部部分没有被格式化的格式问题。由于作者没有以两个空格结束他们的代码行,这意味着它们之间插入了一个空格而不是换行符。
  • @GarethPW 我修正了格式

标签: python python-3.x nonetype


【解决方案1】:

Python 有一个很酷的小trick,如果没有指定它总是返回 None。因此,如果您编写一个不返回任何内容的函数 hello world,您将得到 None。

例如:

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

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

scalar 方法中没有 return 语句,所以它总是返回 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]

【讨论】:

  • 换句话说,将scalar 方法中的new_coordinates = ... 更改为return ... 将解决此问题。
  • @o_o 将此添加到答案中
  • 感谢大家 - 缺少退货线路是根本原因。感谢您对绝对初学者的帮助和耐心。
【解决方案2】:

问题是你试图从scalar 获取一个值,即使它没有返回任何东西。我不完全确定您要返回什么,因此您必须自己处理。

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

my_vector = Vector([1,2])

my_vector.normalized()

【讨论】:

  • 不是问题的根源,而是我承认的问题。
  • 这在技术上是个问题吗?从具有类实例作为第一个参数的类调用类方法将应用具有实例为self 的函数。虽然作者可能不想以这种方式使用该函数,但这并不是真正的“错误”。
  • @o_o 我想你是对的。作为评论,这可能会更好。
  • @GarethPW:感谢您指出这一点。感谢您的反馈!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-21
  • 2020-11-16
相关资源
最近更新 更多