3

Difference between create instance of an objects by () and without parentheses?

Assume this is my simple class:

class ilist(list):
    t1 = "Test1"
    t2 = "Test2"

And making the instances to this two variables:

list1 = ilist()
list2 = ilist

When print the two instances

>>> list1
[]
>>> list2
<class '__main__.ilist'>

I can successfully access their attributes

>>> list1.test1
'Test1'
>>> list2.test1
'Test1'

And it shows error in list2 using a method append

>>> list1.append("Item1")
>>> list2.append("Item1")
Traceback (most recent call last):
File "<pyshell#64>", line 1, in <module>
list2.append("Item1")
TypeError: descriptor 'append' requires a 'list' object but received a 'str'

What is the difference not only in this simple example?

1
  • Only one of them creates an instance, Commented Jun 4, 2013 at 22:02

5 Answers 5

12

list1 = ilist() creates an object of the class. list2 = ilist makes a reference to the class itself. Classes are first-class objects in Python, which means they can be assigned just like any other object.

Because the attributes are part of the class, they're also part of the objects that are created with that class.

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

Comments

2

You aren't creating an instance of an object in your second example. You're just assigning the class ilist to a variable named list2, which is why repr(list) prints out its class name.

Comments

2

When you are not calling the class (omitting the ()), you are not making instances. You are creating another reference to the class. () calls a class to produce an instance.

Your list2 variable is merely a reference to your ilist class object. That class object has both t1 and t1 attributes, so you can reference those. But only list1 is an actual instance, produced by calling the class.

When looking up attributes on an instance, the class is consulted as well. So list1 does not have the t1 and t2 attributes, but its class does.

You may want to consult the Python tutorial on classes again to see what the difference is between classes and instances.

Comments

1

To explain the actual error message: The same method is called in the second example, but methods should receive self as their first argument. If you are calling using an instance, it will be passed as the first argument; but here you are using the class, so it should be passed explicitly.

You are passing "Item1" as the first argument, but that's a string, not an ilist.

Comments

0

(almost) Everything is an object in python, so list1 = ilist() is an object of type ilist and ilist and list2 = ilist are objects of type type

Comments

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.