简体   繁体   English

如何定义具有列表属性的 python class 和接受变量 arguments 的 class 构造函数?

[英]how can I define python class with list attribute and the class constructor that accept variable arguments?

How can I define a python attribute as a class?如何将 python 属性定义为 class? I want to define a Python class that instantiate the objects that are list type.我想定义一个 Python class 来实例化列表类型的对象。 I can do that using __init__ and a class method, but I'm looking for a way to avoid using a method.我可以使用__init__和 class 方法来做到这一点,但我正在寻找一种避免使用方法的方法。 Second question is that I'm wondering if I can define a class with a constructor that accept variable arguments (eg to use this class to instantiate objects with different No of indexes ([4,5,6] and [1,2,3,4,7]). I've copied my code below. Thanks for your help:)第二个问题是我想知道是否可以使用接受变量 arguments 的构造函数定义 class (例如,使用此 class 实例化具有不同索引数的对象([4,5,6] ,4,7])。我在下面复制了我的代码。感谢您的帮助:)

    class SuperList(list):
        def __init__(self, a, b, c):
            self.a = a
            self.b = b
            self.c = c
        def My_list(self):
            return [self.a, self.b, self.c]
    obj1 = SuperList(1, 2, 3)
    List1 = obj1.My_list()
    List1.append(8)
    print(List1)

I am not really sure what you are trying to achieve with the "class generated list" but find below one example that may give you a better understanding.我不确定您要使用“类生成列表”实现什么目标,但可以在下面找到一个示例,该示例可能会让您更好地理解。

As you are inheriting from list , just by doing the following you would have a custom list implementation:当您从list继承时,只需执行以下操作,您将拥有一个自定义列表实现:

class SuperList(list):
    def __init__(self, *args):
        super().__init__(args)

list1 = SuperList(1, 2, 3)
list1.append(8)
print(list1)

list2 = SuperList(1, 2, 3, 7, 8, 9)
list2.append(999)
print(list2)

class SuperList(list):
    def __init__(self,*a):
        self.myList = list(a)
    def My_list(self):
        return self.myList

This works for multiple argument这适用于多个参数

obj1 = SuperList(1, 2, 54, 3)
print(obj1.My_list())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM