Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class() vs self.__class__() when creating object?

Tags:

What are the advantages/disadvantages of using Class() or self.__class__() to create a new object within a class? Is one way generally preferred over the other?

Here is a contrived example of what I am talking about.

class Foo(object):                                                              
  def __init__(self, a):                                                        
    self.a = a                                                                  

  def __add__(self, other):                                                     
    return Foo(self.a + other.a)                                                

  def __str__(self):                                                            
    return str(self.a)                                                          

  def add1(self, b):                                                            
    return self + Foo(b)                                                        

  def add2(self, b):                                                            
    return self + self.__class__(b)                                             
like image 841
Ben J Avatar asked Dec 17 '13 00:12

Ben J


1 Answers

self.__class__ will use the type of a subclass if you call that method from a subclass instance.

Using the class explicitly will use whatever class you explicitly specify (naturally)

e.g.:

class Foo(object):
    def create_new(self):
        return self.__class__()

    def create_new2(self):
        return Foo()

class Bar(Foo):
    pass

b = Bar()
c = b.create_new()
print type(c)  # We got an instance of Bar
d = b.create_new2()
print type(d)  # we got an instance of Foo

Of course, this example is pretty useless other than to demonstrate my point. Using a classmethod here would be much better.

like image 114
mgilson Avatar answered Sep 20 '22 15:09

mgilson