1
  1. How do I store multiple instances of a class objects in a list?

  2. How do I bind a name to a type in Python? In Java, I would do something like this:

    SliceField[] schemaElements = {
        new SliceField("cust", SliceDB.INT),
        new SliceField("name", SliceDB.STRING),
        new SliceField("age", SliceDB.INT),
        new SliceField("phone", SliceDB.STRING),
        new SliceField("address", SliceDB.STRING)
    }
    

How would I do that in Python?

3 Answers 3

1

As for 1), you just need a list.

schemaElements = [SliceField("cust", SliceDB.INT), ..., SliceField("address", SliceDB.STRING)]

Regarding 2), I am not exactly sure what you mean:

  • Should you mean making sure that a variable always has a certain type, there is (a) no (easy) way to do that and (b) it is discouraged (use Duck Typing instead).

  • Should you mean renaming types (like C typedef), just assign them (newName = typeName)

Sign up to request clarification or add additional context in comments.

6 Comments

instead of have SliceDB.INT, i just want it to be bind to Int because here i will not create a class name Slice.INT
So you just want to signal what type that field should have?
so will i have something like schemaElements=[SliceField("cust", int)...]?
Yes. Also, you can use that to automagically convert the values to the right type, because int and str are functions turning values into integers and strings respectively.
it is ok. fixed it. Thank you do much hlt
|
0

You can do this in Python just as well as you can in Java:

 class Test:
     def __init__(self, a, b):
         self.a = a
         self.b = b

 l = [Test(1, 2), Test(3, 4), Test("I declare", "a thumb war")]

 l[0].a
 >>> 1

 l[2].b
 >>> 'a thumb war'

Comments

0

You can do something like this:

schemaElements = [SliceField("cust", SliceDB.INT),....]

While doing so, make sure that the class SliceField has __init__ defined.

class SliceField(value,type):
     def __init__(self, value, type):
         self.value = value
         self.type = type
     # Define other class parameters

If you want SliceField to bind to some particular conditions, you will have to define it inside you class itself.

1 Comment

how can i bind my instance variale to a type, i do not have the Slide.DB class?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.