如何从列表对象中获取变量?

时间:2014-12-14 16:41:04

标签: python list class object

如何从列表对象中获取变量?

例如:

class Ball(object):

    def __init__ (self, x, y):
        self.x = x
        self.y = y

ball = Ball(x, y)
list = [ball]

是这样的吗?:

a = list[0]
b = list[1]

因此print(a, b)会打印x, y

2 个答案:

答案 0 :(得分:3)

class Ball(object):

    def __init__ (self, x, y):
        self.x = x
        self.y = y

    def display(self):
        return self.x, self.y


ball = Ball('This is x value', 'This is y value')
a, b = ball.display()
print a, b

__init__应始终返回None,因此您必须创建一个新方法来返回x和y。

您不能尝试从__init__这样的方法返回:

class Ball(object):

    def __init__ (self, x, y):
        self.x = x
        self.y = y
        return self.x, self.y

a, b = Ball('This is x value', 'This is y value')
print a, b

会给你例外:

TypeError: __init__() should return None, not 'tuple'

答案 1 :(得分:0)

class Ball(object):

    def __init__ (self, x, y):
        self.x = x
        self.y = y

    # add method to get points as tuple (x, y)     
    def get_point(self):
        return (self.x, self.y,)



ball = Ball(x, y)

这将在索引0中创建一个包含单个Ball对象的列表 (名称已更改,因此您无法覆盖builtin list):

ball_list = [ball]

这将使用我们添加的方法和[x, y]tuple的广告素材创建list

ball_point = list(ball.get_point())
相关问题