Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inheritance in python 2.7.x

I did this code:

class Square(Quad):
    def __init__(self, linesValue):
        """Calls the builder in quad (same)"""
        super(Square, self).__init__(linesValue)

then It said I have to send type as first arg, so I did this:

class Square(Quad):
    def __init__(self, linesValue):
        """Calls the builder in quad (same)"""
        super(type(Square), self).__init__(linesValue)

then it said obj must be instance of subinstance of class, and as you can see Square(Quad) it is.

like image 592
user2410243 Avatar asked Nov 17 '13 18:11

user2410243


People also ask

Does python 2.7 support classes?

Python classes provide all the standard features of Object Oriented Programming: the class inheritance mechanism allows multiple base classes, a derived class can override any methods of its base class or classes, and a method can call the method of a base class with the same name.

What is the inheritance in python?

Inheritance allows us to define a class that inherits all the methods and properties from another class. Parent class is the class being inherited from, also called base class. Child class is the class that inherits from another class, also called derived class.

Can you inherit 2 classes in python?

In Python a class can inherit from more than one class. If a class inherits, it has the methods and variables from the parent classes. In essence, it's called multiple inheritance because a class can inherit from multiple classes. This is a concept from object orientated programming.

What is super () __ Init__ in python?

__init__() Call in Python. When you initialize a child class in Python, you can call the super(). __init__() method. This initializes the parent class object into the child class. In addition to this, you can add child-specific information to the child object as well.


1 Answers

Considering your indentation is correct then in Python2 a class should inherit from object, otherwise it would be considered as a classic class. And you can't use super on a classic class.

So, if Quad is defined like this, then it is wrong:

class Quad:
    def __init__(self, x):
       pass

And instantiating Square will raise error like this:

>>> Square(12)
    ...
    super(Square, self).__init__(linesValue)
TypeError: must be type, not classobj

Change Quad to inherit from object:

class Quad(object):
    def __init__(self, x):
       print x

Demo:

>>> Square(12)
12
<__main__.Square object at 0x93e286c>
like image 142
Ashwini Chaudhary Avatar answered Oct 20 '22 12:10

Ashwini Chaudhary