user1081715
user1081715

Reputation: 109

Is there a possibility in python to call a classmethod out of the constructor?

Is there a possibility in python to call a classmethod out of the constructor?

I have a method in a class and want to call it while creating a new element.

Is it possible?

  def __init__(self, val1, val2):
    if (val1 == 5) and (val2 == 2):
        function5_2(self)

  def function5_2(self):                
      (arguments)

Upvotes: 0

Views: 114

Answers (2)

NPE
NPE

Reputation: 500367

Yes, it is. Here is an example of a classmethod getting called from a constructor:

class C(object):

  def __init__(self):
    C.func()

  @classmethod
  def func(cls):
    print 'func() called'

C()

Upvotes: 2

mouad
mouad

Reputation: 70031

Yes you can do it:

class Foo(object):

    def __init__(self, a):
        self.a = a
        self.cls_method()

    @classmethod
    def cls_method(cls):
        print 'class %s' % cls.__name__

Output:

class Foo

Upvotes: 4

Related Questions