开发者

Generating a List Class in Python

I am having some problems generating a list for a class in Python. I know there is something simple I'm overlooking, but I just can't figure it out.

My basic code so far:

class Test:
    def  __init__(self,test):
        self.__test = test

My problem is that if I enter

t = Test([1,3,5])

things will work just fine, but if I add

t = Test()

I get an error that I didn't enter enough parameters.

I've tried adding

def __init__(self,test=[])

as a default parameter, which sort of works, but then I don't have unique lists.

I've been looking all over and I can't quite figure out what I'm doing wrong. Any help would be greatly app开发者_运维知识库reciated.


I'm not exactly sure what you're looking for, but you probably want to use None as a default:

class Test:
    def  __init__(self,test=None):
        if test is None:
            self.__test = []
        else:
            self.__test = test


You could use the following idiom:

class Test:
    def  __init__(self,test=None):
        self.__test = test if test is not None else []


Default arguments are evaluated once, when the function is defined, so when you do:

def __init__(self, test=[]):

the 'test' list is shared between all calls to __init__ that don't specify the test argument. What you want is commonly expressed so:

def __init__(self, test=None):
    if test is None:
        test = []

This creates a new list for each invocation where test is not passed an argument (or when it is passed None, obviously.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜