Reputation: 71
I a new learner for python program, and I confuse with creating class instance as following, what are they different?
Class declaration:
class TestClass:
def __init__(self, one=10, two=20, three=30):
self.one = one
self.two = two
self.three = three
1st. (worng)
x = TestClass
print x
print x(50)
print x.one, x.two
output:
__main__.TestClass
<__main__.TestClass instance at 0x0000000002445208>
Traceback (most recent call last):
File "D:\workspace-QATool_vNext\testStudyCode\test\StudyCode.py", line 27, in <module>
print x.one, x.two
AttributeError: class TestClass has no attribute 'one'
2nd. (correct)
y = TestClass()
print y
print y.one, y.two
output:
<__main__.TestClass instance at 0x00000000023B5208>
10 20
Upvotes: 1
Views: 86
Reputation: 16029
The first one gives you a pointer to a class object (yes, these are also objects), the second one an instance to a object.
__init__
is only called when you create a new instance of an object. This is what the ()
after the class do: create a new instance.
You could make your first example work by doing it like this:
x = TestClass #'x' points to class object
print x
z = x(50) #'x' still points to class object but 'z' points to new instance
print z
print z.one, z.two #and 'z' is now usable as a new instance
print x.one #where 'x' still points to the class object that does not know 'one' since it hasn't run '__init__'
The problem was that x still pointed to the class object intead of the newly created instance.
Upvotes: 4
Reputation: 193
The Function init is the constructor for the class and it is not called untill you use following syntex:
y = TestClass()
With that the object of TestClass (i.e. y) has all attributes.
Upvotes: 1
Reputation: 3366
There is a very subtle difference between your two attempts to create and use a TestClass-object.
x = TestClass
This copies the class TestClass to x.
y = TestClass()
This creates an instance of testclass and assigns it to y.
y = x()
By copying the testclass to x, x contains the exact same class and can therefore also be used to initiate objects of the class testclass.
Upvotes: 0
Reputation: 59974
In your first example, you are simply copying the class onto x
. You are not creating an instance at all, and thus, the __init__
constructor does not run. print x(50)
is what is making an instance of the class, because you are actually calling the class. But you have not stored it anywhere, so it is pointless.
In the second one, you are creating an instance (note the paretheses after TestClass
), and thus accessing the variables work as you have discovered
Upvotes: 0