You have the following class hierarchy - python

class A(object):
def foo(self):
print 'hi'
class B(A):
def foo(self):
print 'bye'
Which of these statements are correct?
When a = A() we say that a is an instance of A
When b = B() we say that b is a subclass of A
Both of the above
Neither of the above
I believe that the answer is B.

class B inherits class A.
So class B is a subclass of A.
But when you instantiate A, a = A(), a is indeed an instance of A.
Now, I'm not sure about the wording, since, b = B(), is an instance of B... which is a subclass of A... but an instance is not a class or subclass.
It is instead an instance of A... since B is child of A through inheritance.
So in summary, when you instantiate an object, it is a instance of the class and all of that classes parents. But an object is not a class.

Related

Delegates the Calculation of a Property of a Superclass to its Subclass

In the book, Python in a Nutshell,
the authors claim the following code snippet is problematic:
class B:
def f(self):
return 23
g = property(f)
class C(B):
def f(self):
return 42
c = C()
print(c.g) # prints: 23, not 42
And the solution, as the authors claimed, is to redirect the calculation of property c.g to the class C's implementation of f at the superclass B's level.
class B:
def f(self):
return 23
def _f_getter(self):
return self.f()
g = property(_f_getter)
class C(B):
def f(self):
return 42
c = C()
print(c.g) # prints: 42, as expected
I disagree but please help me to understand why the authors claimed as they did.
Two reasons for my disagreement.
Superclasses are far likely to be in upstream modules and it is not ideal for upstream modules to implement additional indirection to take into account that subclasses in downstream modules may reimplement the getter method for the superclass property.
The calculation of a property of a superclass is done after the instantiation of an instance of the superclass. An instance of the subclass must be instantiated after the instantiation of an instance of the superclass. Therefore, if the writer of C does not explicitly "declare" C.g to be a property with a different implementation C.f, then it should rightly inherits the property B.g and i.e. c.g should be b.g.
My question is:
am I right with this thought or are the authors right with their claims?
This is a slight more in depth explanation of what is happening.
Basically in your first snippet (which is not very idiomatic python), you bind the exising B.f method to B.g, when C inherits g, its still bound to B.f. g is basically statically linked to B.f.
class B:
def f(self):
return 23
g = property(f) # B.f gets bound to B.g as property
class C(B):
def f(self):
return 42
# C.g not redeclared is still bound to B.f
The "correction snippet" is even less idiomatic, and bind a method which will retrieve the f method from self, the instance it is run on, which makes it dynamic because if self's f method is different from B.f, then the result changes. However we still bind statically to a private method.
class B:
def f(self):
return 23
def _f_getter(self):
return self.f()
g = property(_f_getter) # B._f_getter gets bound to B.g, but B._f_getter uses the f method of self
class C(B):
def f(self):
return 42
# C.g is still bound to B._f_getter but the f method of self has changed
This is the idiomatic way of using property, as a decorator around another method. We can use the same principle as above, but rather than declaring a private intermediate method, we can use g as a name directly.
class B:
def f(self):
return 23
#property
def g(self): # no binding the B.g property uses f method of self directly
return self.f()
class C(B):
def f(self):
return 42
# C.g uses f method of self which has changed
"The calculation of a property of a superclass is done after the instantiation of an instance of the superclass. " - NO, the property is declared along with a class declaration and it's tied to a target function in that class.
print(vars(B)['g']) # <property object at 0x7f5f799ebce0>
"An instance of the subclass must be instantiated after the instantiation of an instance of the superclass." - NO again. That's obvious. Declaration and instantiation are different processes.
"Therefore, if the writer of C does not explicitly "declare" C.g to be a property with a different implementation C.f, then it should rightly inherits the property B.g" - It inherits g property object in its state on declaration phase (i.e. tied to B.f function).
So, you naturally have valid options:
to override a property in your subclass
or to declare your initial property object to consider inheritance, which is no bad
class B:
def f(self):
return 23
g = property(lambda self: self.f())
class C(B):
def f(self):
return 42
c = C()
print(c.g) # 42
I don't know about property but why don't you use:
class B:
def f(self):
return 23
#property
def g(self):
return self.f()
class C(B):
def f(self):
return 42
c = C()
print(c.g)
print(type(c.g))
# Output
42
int
It's not the same as your initial code?

Confused in Understanding the flow of execution in Python Classes

I wonder how is class C being executed in this code flow
When none of the flow calls it.
class A:
def fun1(self):
print("This is class A")
class B(A):
def fun2(self):
super().fun1()
print("This is class B")
class C(A):
def fun1(self):
super().fun1()
print("This is class C")
class D(B, C):
def fun1(self):
self.fun2()
print("This is class D")
obj = D()
obj.fun1()
"""
# Result of this code is
This is class A
This is class C
This is class B
This is class D
"""
The method resolution order used is a C3 linearization algorithm, and super itself uses this MRO. The resolution for a type is obtained with the mro() method, and cached in the __mro__ attribute:
>>> D.__mro__
(__main__.D, __main__.B, __main__.C, __main__.A, object)
>>> D.mro()
[__main__.D, __main__.B, __main__.C, __main__.A, object]
Since you call print after calling super, you'll see the reverse of this, i.e. A -> C -> B -> D.
I wonder how is class C being executed in this code flow when none of the flow calls it.
D.fun2 doesn't exist, so obj.fun2() gets resolved (via the MRO) on B instead:
>>> obj = D()
>>> obj.fun2
<bound method B.fun2 of <__main__.D object at 0x7fffe89a3cd0>>
Then in B.fun2, the C.fun1 gets called here:
class B(A):
def fun2(self):
super().fun1() # <-- this resolves to C.fun1, not A.fun1!
print("This is class B")
C.fun1 is called since it's D's MRO which is active here, not B's, because the type(self) is D. Note that super() does not always resolve on the parent class, it can be resolved on a sibling class like in your example. Python's implementation was more or less lifted from another programming language called Dylan, where super was named next-method, a less confusing name in my opinion.

Python inherit the property of one class to another

I have three different class's and some variables in it
class A(object):
a = "Hello"
b = "World"
class B(object):
a = "Hello"
b = "World"
class C(object):
a = "Hello"
b = "World"
Where a = "Hello" and b = "World" is common to all class's, how can I declare these variables as a global class and Inherit the properties to these tables.
I Tried in this way, but am not able to get the solution.
class G(object):
a = "Hello"
b = "World"
class A(object, G):
pass
Here I'm trying to inherit the whole property of the class. Please help me to solve this thanks in advance.
class A(object):
a = "Hello"
b = "World"
class B(A):
something
class C(B):
something
c = C()
print(c.a,c.b)
You don't have to re-declare a and b each time or else why would you inherit in the first place. If you declare them you basically are overwriting the parent's variable with the child's. If you do that you can call the parent's one with super().
This is how you do it. Please let know in comments if there is something that you don't understand, or if I am doing anything wrong.
class A(object):
a = "Hello"
b = "World"
class B(A):
pass
class C(B):
pass
c = C()
print(c.a,c.b)
Prints Hello World
Define class A as:
class A(G):
pass
The problem with repeating the base class object is that it creates a base class resolution conflict, since A was inheriting it twice: Once directly, and once indirectly through class G.

callable object as method of a class - Can I get `self` to be the class that owns the method?

In python, a class instance can be used almost like a function, if it has a __call__ method. I want to have a class B that has a method A, where A is the instance of a class with a __call__ method. For comparison, I also define two other methods foo and bar in the "traditional" way (i.e. using def). Here is the code:
class A(object):
def __call__(*args):
print args
def foo(*args):
print args
class B(object):
A = A()
foo = foo
def bar(*args):
print args
When I call any of the methods of B, they are passed a class instance as implicit first argument (which is conventionally called self).
Yet, I was surprised to find that b.A() gets passed an A instance, where I would have expected a B instance.
In [13]: b = B()
In [14]: b.A()
(<__main__.A object at 0xb6251e0c>,)
In [15]: b.foo()
(<__main__.B object at 0xb6251c0c>,)
In [16]: b.bar()
(<__main__.B object at 0xb6251c0c>,)
Is there a way (maybe a functools trick or similar) to bind A() in such a way that b.A() is passed a reference to the b object?
Please note that the example presented above is simplified for the purpose of illustrating my question. I'm not asking for advice on my actual implementation use case, which is different.
Edit: I get the same output, if I define my class B like this:
class B(object):
def __init__(self):
self.A = A()
foo = foo
def bar(*args):
print args
The problem with your code is:
class B(object):
A = A()
class B has a member named A that is an instance of A. When you do B.A(), it calls the method __call__ of that A instance (that is confusingly named A); and since it is an A all the time, and A's method, of course the actual object in args is an A.
What you're after is a descriptor; that is, A should have the magic method __get__; :
class A(object):
def __get__(self, cls, instance):
print(cls, instance)
return self
class B(object):
a = A()
b = B()
c = b.a
Now when b.a is executed, __get__ method gets B and b as the cls and instance arguments, and whatever it returns is the value from the attribute lookup (the value that is stored in c) - it could return another instance, or even a function, or throw an AttributeError - up to you. To have another function that knows the B and b; you can do:
class A(object):
def __get__(self, cls, instance):
if instance is not None:
def wrapper():
print("I was called with", cls, "and", instance)
return wrapper
return self
class B(object):
a = A()
B.a()
The code outputs:
I was called with <__main__.B object at 0x7f5d52a7b8> and <class '__main__.B'>
Task accomplished.

python can we override a method by inheriting 2 class

class A(object):
def print_some(self):
print 'a'
class B(object):
def print_some(self):
print 'b'
class C(A, B):
pass
c = C()
print c.print_some()
'a'
What i expect of the output is 'b'. The reason i want to do this is because i want to override some method, let's say form_valid from CreateView in django, simply by inheriting a class i write containing custom form_valid, or there are better approaches?
class A is first (left) in the class C(A, B) instruction, so you are getting the print_some method from it (A class). Read here.
From your question I expect you can change the inheritance of B and C, can't you? So why don't you build up the inheritance like
A <- B <- C
Or in code:
class A(object):
....
class B(A):
...
class C(B):
...
This should give you the desired output.

Categories