New way of class creation using "type"

Home Forums Python Programming New way of class creation using "type"

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #1940 Reply
    Humble
    Keymaster

    We were following below syntax to create a class :

    >>>> class sports():
    ...     def __init__(self):
    ...             print "I am constructor"
    ... 
    >>> type(sports)
    <type 'classobj'>
    
    
    How-ever its also possible to create a class using "type" as shown below.
    
    type requires 3 arguments..
    
    
    
    First arg: This should be the name of the class
    
    Second arg: This should be the tuple from where the new class is inheriting.. This can be a just a placeholder though with ().
    
    Third arg : This is the dictionary of variables and functions which this class holds..
    
    For ex:
    
    
    >>>> def footm(self):
    ...     print "I am football"
    ... 
    >>> football = type("football", (sports,object),{"foot":footm, "x":5})
    >>> sports
    <class __main__.sports at 0x7f7ad30c7bb0>
    
    
    
    Obviously method of resolution will be in this order:
    
    
    >(<class '__main__.football'>, 
    <class __main__.sports at 0x7f7ad30c7bb0>,
     <type 'object'>)
    
    
    Now, we can get methods and variables ..
    
    
    
    >>>> f=football()
    I am constructor
    
    >>> f.foot()
    I am football
    >>><
    
    
    hope it helps!
    #1964 Reply
    Humble
    Keymaster

    Please understand , this is really useful for dynamic class creation, how-ever may not be suitable for longer class declarations..

Viewing 2 posts - 1 through 2 (of 2 total)
Reply To: New way of class creation using "type"
Your information: