user3739941
user3739941

Reputation:

What is the difference between using "()" and not using it in object definition?

As you see below I define a class named Person with two members named age and name:

>>> class person:
    age = None
    name = None

then I define two object of this class as below:

>>> p1 = person
>>> p2 = person()

My question is what is the difference between p1 and p2:

>>> p1
<class __main__.person at 0x0328FF80>
>>> p2
<__main__.person instance at 0x03273738>
>>> 

They act equal:

>>> p1.age = 19
>>> p1.name = "Steve"
>>> p2.age = 20
>>> p2.name = "Jimme"
>>> p1.age
19
>>> p1.name
'Steve'
>>> p2.age
20
>>> p2.name
'Jimme'
>>> 

Upvotes: 1

Views: 58

Answers (1)

juanchopanza
juanchopanza

Reputation: 227618

Person is a class. The expression Person() creates an instance of that class. So the difference between p1 and p2 is that p1 is a reference to a class, and p2 is an reference to an instance of that class. For example, you can use p1 to instantiate other Person objects:

>>> p3 = p1()
>>> p3
<__main__.person instance at 0x10c9403f8>

If person had instance variables you might observe a difference. In your case, name and age are class variables. That means they are shared by all instances of the person class. It is unlikely this is the behaviour you want.

>>> p1 = person
>>> p2 = person()
>>> p1.name = 'bob'
>>> p1.name
'bob'
>>> p2.name
'bob'
>>> person.name
'bob'

As you can see, all new persons now are called bob.

Here's a slightly more reasonable person class, that can still be instantiated with empty ():

class Person(object):
  def __init__(self, name='bill', age=42):
    self.name = name
    self.age = age

Here, name and age are instance variables.

>>> p1 = Person
>>> p2 = Person()
>>> p3 = Person('fred')
>>> p1.name
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: type object 'Person' has no attribute 'name'
>>> p2.name
'bill'
>>> p3.name
'fred'

Upvotes: 3

Related Questions