BLUC
BLUC

Reputation: 2691

Why is it bad to use data types to initialize instances in Python?

Sorry if the answer to this is obvious, but I want to be sure, if you have(in Python):

class Name(object):

    def __init__(self):
        self.int_att1 = 0
        self.int_att2 = 0
        self.list_att = []

why can't(I know you can, but I've never seen a programmer do this) you initialize it in this way:

class Name(object):

    def __init__(self):
        self.int_att1 = int
        self.int_att2 = int
        self.list_att = list

Are there bad effects that come out of this? What makes the former more Pythonic?

My best guess is because Python needs a value for instance.attribute. But if this is the case than why is it that using datatype works?

Upvotes: 1

Views: 207

Answers (3)

Mark Ransom
Mark Ransom

Reputation: 308138

From The Zen of Python: "Explicit is better than implicit."

You could certainly initialize with the default value of a type (not the type itself as in your example), but explicit is better than implicit. When you initialize with an actual value, there's no doubt about what you're getting.

Upvotes: 0

juliomalegria
juliomalegria

Reputation: 24921

When you do self.int_att1 = int, the attribute int_att1 now references to the type int, I mean, is just another name for int. And I'll prove this in a simple way:

>>> number_type = int
>>> i = number_type()
>>> i
0
>>> type(i)
<type 'int'>

In this code, number_type becomes a "synonym" for the type int, that's why when I asked the type of i, it returned int and not number_type.

Same for self.list_att = list.


Probably, what you wanted to do was:

class Name(object):

    def __init__(self):
        self.int_att1 = int()
        self.int_att2 = int()
        self.list_att = list()

This is totally different, you are not longer assigning the type to the attribute. Instead, you are assigning the initial value of that type. Let's see what those initial values are:

>>> initial_int = int()
>>> initial_int
0
>>> initial_list = list()
>>> initial_list
[]

So, we can clearly see that the initial value of the type int is 0 and the initial value of the type list is [], and that is exactly what you were looking for!

Upvotes: 4

Matthew Flaschen
Matthew Flaschen

Reputation: 284796

You can, but it has a totally different effect. In the second case, you're setting the attribute equal to the value of the type, which is usually not what you want. In Python types are objects too, so this is legal.

It would let you do something like:

n = Name()

v = n.int_att1()

v would then be 0, because that's the value constructed by int's no-arg constructor.

Upvotes: 2

Related Questions