class based view in django - python

I am trying to understand class based view concepts in django. Before that i should know the function call and return statement.I would like to know what it does which I mentioned below code. I know that is about to call parent class function. what should it return. Can anyone explain this concepts with example. Thanks in advance.
class Foo(Bar):
def baz(self, arg):
return super(Foo, self).baz(arg)

I am explaining this with example.
I am creating two classes which one is inheriting from other.
class Parent(object):
def implicit(self):
print "PARENT implicit()"
class Child(Parent):
pass
dad = Parent()
son = Child()
>>>dad.implicit()
>>>son.implicit()
"PARENT implicit()"
"PARENT implicit()"
This creates a class named Child but says that there's nothing new to define in it. Instead it will inherit all of its behavior from Parent.
Now next example
class Parent(object):
def override(self):
print "PARENT override()"
class Child(Parent):
def override(self):
print "CHILD override()"
dad = Parent()
son = Child()
>>>dad.override()
>>>son.override()
"PARENT override()"
"CHILD override()"
Even though Child inherits all behaviour from Parent, Child.override messages because son is an instance of Child and Child overrides that function by defining its own version
Now next example,
class Parent(object):
def altered(self):
print "PARENT altered()"
class Child(Parent):
def altered(self):
print "CHILD, BEFORE PARENT altered()"
super(Child, self).altered()
print "CHILD, AFTER PARENT altered()"
dad = Parent()
son = Child()
>>>dad.altered()
>>>son.altered()
"PARENT altered()"
"CHILD, BEFORE PARENT altered()"
"PARENT altered()"
"CHILD, AFTER PARENT altered()"
Here we can find super(Child, self).altered(), which is aware of inheritance and will get the Parent class.(Not caring overriding)
Hope this helps
Update..In python3
super().altered() can use instead of super(Child, self).altered()
For more http://learnpythonthehardway.org/book/ex44.html

class Foo(Bar):#here Bar is your super class, you inherit super class methods
def baz(self, arg):#this class method
return super(Foo, self).baz(arg)# here super is mentioned as super class of Foo .baz(arg) is you call the super user method baz(arg)
so u need to create super class like
class BAR(object):
def baz(self,arg):
c=10+20
return c
simple example for two base class
class bar(object):
def baz(self, arg):
print"this is bar class"
class bar1(object):
def baz1(self,arg):
print "this is bar1 class"
class Foo(bar,bar1):
def baz(self, arg):
super(Foo, self).baz1(arg)
super(Foo, self).baz(arg)
a=Foo()
a.baz("hai")

Related

Python multiple inheritance, initializing from a common subclass

How can I make a common subclass initialize all parent classes it's inheriting from?
class Mom(object):
def __init__(self):
print("Mom")
class Dad(object):
def __init__(self):
print("Dad")
class Child(Mom, Dad):
def __init__(self):
super(Child, self).__init__()
c = Child() #only prints Mom
They are missing the super() calls in the Mom and Dad classes that are required for co-operative subclassing to work.
class Mom(object):
def __init__(self):
super(Mom, self).__init__()
print("Mom")
class Dad(object):
def __init__(self):
super(Dad, self).__init__()
print("Dad")
class Child(Dad, Mom):
def __init__(self):
super(Child, self).__init__()
c = Child() # Mom, Dad
You need to call super in Mom's __init__ as well.

Python: automatically call a parent function after child instantiation

Python 2.7
I would like to automotically call a function of a parent object after I instantiate its child
class Mother:
def __init__(self):
pass
def call_me_maybe(self):
print 'hello son'
class Child(Mother):
def __init__(self):
print 'hi mom'
# desired behavior
>>> billy = Child()
hi mom
hello son
Is there a way I can do this?
Edit, from a comment below:
"i should have made it more clearer in my question, what i really want is some sort of 'automatic' calling of the parent method triggered solely by the instantiation of the child, with no explicit calling of the parent method from the child. I was hoping there would be some sort of magic method for this but i dont think there is."
You could use super but you should set your superclass to inherit from object:
class Mother(object):
# ^
def __init__(self):
pass
def call_me_maybe(self):
print 'hello son'
class Child(Mother):
def __init__(self):
print 'hi mom'
super(Child, self).call_me_maybe()
>>> billy = Child()
hi mom
hello son
Use super()?
class Child(Mother):
def __init__(self):
print 'hi mom'
super(Child, self).call_me_maybe()
Since the child class inherits the parents methods, you can simply call the method in the __init__() statement.
class Mother(object):
def __init__(self):
pass
def call_me_maybe(self):
print('hello son')
class Child(Mother):
def __init__(self):
print('hi mom')
self.call_me_maybe()

Calling Parent method directly in Python

I have a testmethod in the GParent class which is inherited by Parent and Child..
How can I do that?
I tried this but its not working...
GParent.testmethod(self)
class GParent():
def testmethod(self):
print "This is test method"
class Parent():
def testmethod(self):
print "This is test method"
class Child(Parent):
def __init__(self):
print "This is init method"
GParent.testmethod(self)
c = Child()
first of all: https://docs.python.org/2/tutorial/classes.html#inheritance
At any rate...
GParent.testmethod(self) <-- calling a method before it is defined
class GParent(): <-- always inherit object on your base class to ensure you are using new style classes
def testmethod(self):
print "This is test method"
class Parent(): <-- not inheriting anything
def testmethod(self): <-- if you were inheriting GParent you would be overriding the method that is defined in GParent here.
print "This is test method"
class Child(Parent):
def __init__(self):
print "This is init method"
GParent.testmethod(self) <-- if you want to call the method you are inheriting you would use self.testmethod()
c = Child()
Take a look at this code and run it, maybe it will help you out.
from __future__ import print_function #so we can use python 3 print function
class GParent(object):
def gparent_testmethod(self):
print("Grandparent test method ")
class Parent(GParent):
def parent_testmethod(self): #
print("Parent test method")
class Child(Parent):
def child_testmethod(self):
print("This is the child test method")
c = Child()
c.gparent_testmethod()
c.parent_testmethod()
c.child_testmethod()
You cannot call GParent's testmethod without an instance of GParent as its first argument.
Inheritance
class GParent(object):
def testmethod(self):
print "I'm a grandpa"
class Parent(GParent):
# implicitly inherit __init__()
# inherit and override testmethod()
def testmethod(self):
print "I'm a papa"
class Child(Parent):
def __init__(self):
super(Child, self).__init__()
# You can only call testmethod with an instance of Child
# though technically it is calling the parent's up the chain
self.testmethod()
# inherit parent's testmethod implicitly
c = Child() # print "I'm a papa"
However, two ways of calling a parent's method explicitly is through composition or class method
Composition
class Parent(object):
def testmethod(self):
print "I'm a papa"
class Child(object):
def __init__(self):
self.parent = Parent()
# call own's testmethod
self.testmethod()
# call parent's method
self.parentmethod()
def parentmethod(self):
self.parent.testmethod()
def testmethod(self):
print "I'm a son"
c = Child()
Class method
class Parent(object):
#classmethod
def testmethod(cls):
print "I'm a papa"
class Child(object):
def __init__(self):
# call own's testmethod
self.testmethod()
# call parent's method
Parent.testmethod()
def testmethod(self):
print "I'm a son"
c = Child()
It has become advisory to use composition when dealing with multiple inheritance, since inheritance creates dependency to the parent class.

How to call super method from grandchild class?

I am working with some code that has 3 levels of class inheritance. From the lowest level derived class, what is the syntax for calling a method 2 levels up the hierarchy, e.g. a super.super call? The "middle" class does not implement the method I need to call.
Well, this is one way of doing it:
class Grandparent(object):
def my_method(self):
print "Grandparent"
class Parent(Grandparent):
def my_method(self):
print "Parent"
class Child(Parent):
def my_method(self):
print "Hello Grandparent"
Grandparent.my_method(self)
Maybe not what you want, but it's the best python has unless I'm mistaken. What you're asking sounds anti-pythonic and you'd have to explain why you're doing it for us to give you the happy python way of doing things.
Another example, maybe what you want (from your comments):
class Grandparent(object):
def my_method(self):
print "Grandparent"
class Parent(Grandparent):
def some_other_method(self):
print "Parent"
class Child(Parent):
def my_method(self):
print "Hello Grandparent"
super(Child, self).my_method()
As you can see, Parent doesn't implement my_method but Child can still use super to get at the method that Parent "sees", i.e. Grandparent's my_method.
This works for me:
class Grandparent(object):
def my_method(self):
print "Grandparent"
class Parent(Grandparent):
def my_method(self):
print "Parent"
class Child(Parent):
def my_method(self):
print "Hello Grandparent"
super(Parent, self).my_method()
If you want two levels up, why not just do
class GrandParent(object):
def act(self):
print 'grandpa act'
class Parent(GrandParent):
def act(self):
print 'parent act'
class Child(Parent):
def act(self):
super(Child.__bases__[0], self).act()
print 'child act'
instance = Child()
instance.act()
# Prints out
# >>> grandpa act
# >>> child act
You can add something defensive like checking if __bases__ is empty or looping over it if your middle classes have multiple inheritance. Nesting super doesn't work because the type of super isn't the parent type.
You can do this by following ways
class Grandparent(object):
def my_method(self):
print "Grandparent"
class Parent(Grandparent):
def my_other_method(self):
print "Parent"
class Child(Parent):
def my_method(self):
print "Inside Child"
super(Child, self).my_method()
In this case Child will call base class my_method but base class my_method is not present there so it will call base class of parent class my_method in this way we can call my_method function of grandparent
Another Way
class Grandparent(object):
def my_method(self):
print "Grandparent"
class Parent(Grandparent):
def my_other_method(self):
print "Parent"
class Child(Parent):
def my_method(self):
print "Inside Child"
super(Parent, self).my_method()
In this way we are directly calling function base class my_method function of the parent class
Another way but not pythonic way
class Grandparent(object):
def my_method(self):
print "Grandparent"
class Parent(Grandparent):
def my_other_method(self):
print "Parent"
class Child(Parent):
def my_method(self):
print "Inside Child"
Grandparent.my_method()
In this way we are directly calling my_method function by specifying the class name.
Made and tested in python 3
class Vehicle:
# Initializer / Instance Attributes
def __init__(self, name, price):
self.name = name
self.price = price
# instance's methods
def description(self):
print("\nThe car {} has a price of {} eur".format(self.name, self.price))
#Object Vehicle
m3 = Vehicle("BMW M3", 40000)
m3.description()
class Camper(Vehicle):
def __init__(self,nome,prezzo,mq):
super().__init__(nome,prezzo)
self.mq=mq
# instance's methods
def description(self):
super().description()
print("It has a dimension of",format(self.mq)+" mq")
#Camper Object(A camper is also a Vehicle)
marcopolo=Camper("Mercede MarcoPolo",80000,15)
marcopolo.description()
Output:
The car BMW M3 has a price of 40000 eur
The car Mercede MarcoPolo has a price of 80000 eur
It has a dimension of 15 mq

Call a parent class method from a child class in Python 2

I want to call parent class method using super() in Python 2.
In Python 3, I'd code it like this:
class base:
#classmethod
def func(cls):
print("in base: " + cls.__name__)
class child(base):
#classmethod
def func(cls):
super().func()
print("in child: " + cls.__name__)
child.func()
with this output:
in base: child
in child: child
However, I have no idea, how do this in Python 2. Of course, I can use base.func(), but I don't like to specify parent class name in addition and mainly I get unwanted result:
in base: base
in child: child
With cls (cls is child) as first argument in super() function call, I get this error:
TypeError: must be type, not classobj
Any idea how do it using super() or analogous function in which I don't have to specify name of parent class?
furthering the other answer you can do classmethods for it like
class base(object):
#classmethod
def func(cls):
print("in base: " + cls.__name__)
class child(base):
#classmethod
def func(cls):
super(cls, cls).func()
print("in child: " + cls.__name__)
child.func()
You parent object needs to inherit from object in python 2. So:
class base(object):
def func(self):
print("in base")
class child(base):
def func(self):
super(child, self).func()
print("in child")
c = child()
c.func()
I was trying to do something similar where I was trying to basically "walk up" the inheritance chain until I found a certain base class and then do something there with the class name. The issue I was having was that ALL of these answers assume that you know the name of the class you are trying to get the super of. I tried the "super(cls, cls)" approach but got the "inifinite recursion" issue described above. Here is where I landed
#classmethod
def parent_name(cls):
if BaseDocument in cls.__bases__:
# This will return the name of the first parent that subclasses BaseDocument
return cls.__name__
else:
for klass in cls.__bases__:
try:
parent_name = klass.parent_name()
if parent_name is not None:
return parent_name
except AttributeError:
pass
return None

Categories