views:

54

answers:

2

I am a Python noob.

I create a class as follows:

class t1:
    x = ''
    def __init__(self, x):
        self.x = x

class t2:
    y = ''
    z = ''
    def __init__(self, x, y, z):
        self.y = t1.__init__(x)
        self.z = z

Now contrary to C++ or Java, I do not bind the data type to y while writing the class definition. It is only because the constructor code is such that it shows that y is of type t1. Can we bind a data type while declaring y?

+6  A: 

No. Variables in Python do not have types - y does not have a type. At any moment in time, y refers to an object, and that object has a type. This:

y = ''

binds y to an object of type str. You can change it later to refer to an object of a different type. y itself has no intrinsic type.

See Fredrik Lundh's excellent "Reset your brain" article for further explanation.

(By the way, this: self.y = t1.__init__(x) is a rather strange piece of code. Did you mean to say self.y = t1(x)?)

RichieHindle
no i meant t1.__init__(x) without the assignment. self.y = t1(x) also makes sense.thanks
iamrohitbanga
*object of type `str`* you mean.
SilentGhost
@SilentGhost: Thanks - corrected.
RichieHindle
t1.__init__(x) won't work and it is not the same as t1(x).
DavidG
+3  A: 

It's out of the scope, but please note:

class A(object):
    x = None

In this context, x is a class variable, not an instance variable and is shared by each instance. It's commonly used in the borg pattern.

class A(object):
    def __init__(self, x):
        self.y = None
        self.x = x

Here, self.y and self.x are instance variables.

dzen