点操作员表现得很奇怪

时间:2014-07-18 05:54:25

标签: python

我是python app开发的新手。当我尝试代码时,我无法看到它的输出。我的示例代码是:

class name:
    def __init__(self):
        x = ''
        y = ''
        print x,y

当我调用上述函数时

some = name()
some.x = 'yeah'
some.x.y = 'hell'

当我打电话给some.x时它工作正常,但当我打电话给some.x.y = 'hell'时,它显示错误

Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    some.x.y = 'hell'
AttributeError: 'str' object has no attribute 'y'

希望你们能帮助我。

4 个答案:

答案 0 :(得分:2)

xy是您的实例some上的两个不同变量。

当您致电some.x时,您将返回字符串'yeah'。然后你调用.y,你实际上是在尝试'yeah'.y,这就是为什么它说字符串对象没有属性y

所以你想要做的是:

some = name()
some.x = 'hell'
some.y = 'yeah'
print some.x, some.y

答案 1 :(得分:2)

首先,你要以错误的方式定义课程,你应该;

class name:
    def __init__(self):
        self.x = ''
        self.y = ''
        print x,y

然后,你应该采用错误的方式,你应该;

some = name()
some.x = 'yeah'
some.y = 'hell'

问题是,xystrings。如果您出于某种原因想some.x.y,则应自行定义x。换句话说,您暂时无法使用some.x.y

好的,你还需要some.x.y;

class name:
    def __init__(self):
        pass

some = name()
some.x = name()
some.x.y = "foo"

print some.x.y
>>> foo

答案 2 :(得分:0)

这些是不同的变量。因此,当你将.y链接到some.x时,你正在寻找一个不存在的字符串的成员变量y

some = name()
some.x = 'yeah'
some.y = 'hell'

如果你想用x和y制作单个字符串,你可以使用+将它们连接在一起,如下所示

s = some.x + ' ' + some.y
print s # prints out "yeah hell"

class name:
    def __init__(self):
        x = ''
        y = ''
    def ___str__(self):
        print x + ' ' y

现在你可以打印课程并获得

print some # prints "yeah hell"

答案 3 :(得分:0)

当您执行some.x时,您不再处理some,而是处理some.x所属的类型。由于'foo'.y没有意义,因此您无法使用some.x,因为它与'foo'属于同一类型。