parent class self.__class__.__name__ prints name of child class - python

I have 2 classes: a and b. 'b' inherits from 'a'. How do i get class 'a' to print it's actual name? In the case below, it prints the name of the child class.
class a():
def __init__(self):
print("a -> " + self.__class__.__name__)
class b(a):
def __init__(self):
super().__init__()
print("b -> " + self.__class__.__name__)
bo = b()
prints:
a -> b
b -> b

You can use the __class__ variable (not attribute) available in all methods defined in a class block. So:
In [1]: class a():
...: def __init__(self):
...: print("a -> " + __class__.__name__)
...:
...: class b(a):
...: def __init__(self):
...: super().__init__()
...: print("b -> " + __class__.__name__)
...:
...:
In [2]: b()
a -> a
b -> b
Out[2]: <__main__.b at 0x10ce853a0>
This is part of the Python data model and it was added to allow the no-arg form of super() that became available in Python 3.
__class__ is an implicit closure reference created by the compiler
if any methods in a class body refer to either __class__ or super.
This allows the zero argument form of super() to correctly identify
the class being defined based on lexical scoping, while the class or
instance that was used to make the current call is identified based on
the first argument passed to the method.
So note, this won't be available for dynamically added methods:
In [4]: a.a_method = a_method
In [5]: b().a_method()
a -> a
b -> b
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-5-5887c7d36b49> in <module>
----> 1 b().a_method()
<ipython-input-3-daf632bde4e5> in a_method(self)
1 def a_method(self):
----> 2 print(__class__)
3
NameError: name '__class__' is not defined

The problem is that when you create bo, it's initialized as an object of type b. This means that for bo, the self variable whether it's used in the a class or the b class, will be of type b.
One alternative is to call .__name__ on the class itself rather than on self:
class a():
def __init__(self):
print("a -> " + a.__name__)
class b(a):
def __init__(self):
super().__init__()
print("b -> " + b.__name__)
bo = b()
>>> a -> a
>>> b -> b
However, at that point, you might as well hardcode the print statements.

Related

How to access objects from a different class?

There are three classes :
A, B and C
The __init__ of B creates an object of A. Using the mutators, I will be able to change the attributes of A from B for the instance created.
However, I am not unable to find any way to use that instance of A created by B to be used in C without passing the Object explicitly to the __init__ method [ not C.__init(self, object: A) ]
Is there any way to implicitly allow C to use that instance of A ?
I am new to python and not sure if this a valid question. I have looked at other sources where it explicitly passes the object to class C
class A:
def __init__(self):
x = []
y = []
class C :
def __init__(self):
#[get obj1 without passing the instance in init]
self.value = None
def method1():
self.value = len([]) #len(obj1 of A.x)
class B:
def __init__(self):
obj1 = A()
obj1.x = [1,2,3,4]
obj1.y = [1,2,3]
obj2 = B()
print(obj2.value) #this should be the length of x in the instance A created above
Here is a simple example:
class A:
def __init__(self, i = ""):
self.item = i
class B:
def __init__(self):
self.a = A("hello")
class C:
def __init__(self):
b = B()
print(b.a.item)
c = C()
Output:
hello
Let's say we have classes A and B:
class A:
def hello_world(self):
print("hello world")
class B:
def __init__(self):
self.a = A()
def hello_world(self):
self.a.hello_world()
You create an instance of class B (which will create an instance of class A inside):
b = B()
You can then pass a reference to either b or b.a to any function of an instance of class C (either a constructor or not)
class C:
def hello_world(self, a):
a.hello_world()
c = C()
c.hello_world(b.a)
You can also use global variables:
class C:
def hello_world(self):
b.a.hello_world()
c = C()
c.hello_world()
Here the instances of class C will rely on variable b to be in place and just use its a attribute.
Using global variables in classes is generally considered to be hard to maintain and a bad practice. If your class depends on a value or an instance of some class you should pass the reference in the constructor (__init__ function) or in the function that's using it.
If these classes are in different different python files then you can also use these classes by importing the class name and creating an object of that class:
eg:
file1.py
class A:
def __init__(self):
x = []
y = []
file2.py
from file1 import A
class C :
def __init__(self):
[get obj1 without passing the instance in init]
self.value = None
self.obj_a = A()
def xyz(self):
print "in class c"
file3.py
from file2 import C
from file1 import A
Class B:
def __init__(self):
self.obj_a = A()
self.obj_c = C()
def another_func(self):
print self.obj_c.xyz()# it will print "in class c"

Python: Call for value inside nested class

I'm trying to call for value from class B that is nested in class A and use it in class C.
I'm getting AttributeError:
class A():
class B():
a = 1
class C():
b = 2
c = B.a + b
AttributeError: class B has no attribute 'a'
I also tried to call From 'A', Pycharm recognize it, but python still get AttributeError:
class A(object):
class B(object):
a = 1
class C(object):
b = 2
c = A.B.a + b
AttributeError: class A has no attribute 'B'
Does someone have an idea of how to use it?
Thanks
The problem is that the class template (A) is not constructed while you're calling A.B.a. That is, A is not bound yet to a class.
Try this workaround:
class A():
class B():
a = 1
Now create C separately (A is already defined):
class C():
b = 2
c = A.B.a + b
And reference C from A:
A.C = C
This can possibly be done via meta-classes, but could be an over-kill here.
At compile time, the class definition for class A is not complete hence you can not access the classes, variables and methods defined in a parent class inside a nested class.
You can try separating the class definitions though as suggested by #Reut Sharabani.
You can not access the class by its name, while the class definition statement is still executed.
class A(object):
class B(object):
a = 1
class C(object):
b = 2
c = A.B.a + b # here class A statement is still executed, there is no A class yet
To solve the problem you must defer the execution of those statements :
move the all those statements to a classmethod
call them after the classes was defined.
class A(object):
class B(object):
#classmethod
def init(cls):
cls.a = 1
class C(object):
#classmethod
def init(cls):
cls.b = 2
cls.c = A.B.a + cls.b
#classmethod
def init(cls):
cls.B.init()
cls.C.init()
A.init()

Accessing higher-level class from nested class in Python

Suppose I have two Python classes, A and B, and that B is an attribute of A. Can a method of B modify a property of A? for example, I would like to be able to call
A.B.setXinA(1)
A.x
>>> 1
One way around it would be embed a reference to A in B:
A.B.reftoA = A
But that's rather ugly... Is there a way to access the higher-level class directly? Below is a working example using the second method:
class A:
def __init__(self, b):
b.parent = self
setattr(self, b.name, b)
class B:
def __init__(self, name):
self.name = name
b = B('abc')
a = A(b) # b is now a.abc
abc.parent.x = 1
a.x
>>> 1
What about a method in B like this:
class B:
def __init__(self, name):
self.name = name
def setXinA(self, x):
self.parent.x = x
Then:
>>> b = B('abc')
>>> a = A(b)
>>> b.setXinA(19)
>>> print(A.x)
19
This way requires that setXinA is called by an instance of B rather than just B.setXinA(42) for example. Also, it sets x as an attribue of the class A, rather than any particular instance of A.

Python: nested class with static method fails

What is wrong with the following code?
class A:
def A_M(self): pass
class B:
#staticmethod
def C(): super(B).A_M()
error (Python 2.7.3):
>>> a = A()
>>> a.B.C()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "..x.py", line 36, in C
def C(): super(B).A_M()
NameError: global name 'B' is not defined
Edit:
the solution was simple as this:
class A:
def A_M(self): pass
class B:
#staticmethod
def C(): A().A_M() #use of A() instead of supper, etc.
Important Note that there is an issue with this solution. If you change the name of super class (i.e. A) then you will have to update all uses inside itself as A :)).
class A(object):
def foo(self):
print('foo')
#staticmethod
def bar():
print('bar')
class B(object):
#staticmethod
def bar(obj):
# A.foo is not staticmethod, you can't use A.foo(),
# you need an instance.
# You also can't use super here to get A,
# because B is not subclass of A.
obj.foo()
A.foo(obj) # the same as obj.foo()
# A.bar is static, you can use it without an object.
A.bar()
class B(A):
def foo(self):
# Again, B.foo shouldn't be a staticmethod, because A.foo isn't.
super(B, self).foo()
#staticmethod
def bar():
# You have to use super(type, type) if you don't have an instance.
super(B, B).bar()
a, b = A(), B()
a.B.bar(a)
b.foo()
B.bar()
See this for details on super(B, B).
You need to use a fully-qualified name. Also, in python 2.7, you need to use (object), else super(A.B) will give TypeError: must be type, not classobj
class A(object):
def A_M(self):
pass
class B(object):
#staticmethod
def C():
super(A.B).A_M()
Finally, super(A.B) is essentially object here. Did you mean for B to inherit from A? Or were you simply looking for A.A_M()?
A latecommer, to just encapsulate B in A the easy way is this:
class A:
def A_M(self):
return "hi"
class B:
#staticmethod
def C():
return A().A_M()
a = A()
print a.B().C()
Not sure this is what you need, but the question was still unsolved, so I guessed.

Python object conversion

Assume that we have an object k of type class A. We defined a second class B(A). What is the best practice to "convert" object k to class B and preserve all data in k?
This does the "class conversion" but it is subject to collateral damage. Creating another object and replacing its __dict__ as BrainCore posted would be safer - but this code does what you asked, with no new object being created.
class A(object):
pass
class B(A):
def __add__(self, other):
return self.value + other
a = A()
a.value = 5
a.__class__ = B
print a + 10
a = A() # parent class
b = B() # subclass
b.value = 3 # random setting of values
a.__dict__ = b.__dict__ # give object a b's values
# now proceed to use object a
Would this satisfy your use case? Note: Only the instance variables of b will be accessible from object a, not class B's class variables. Also, modifying variables in a will modify the variable in b, unless you do a deepcopy:
import copy
a.__dict__ = copy.deepcopy(b.__dict__)
class A:
def __init__(self, a, b):
self.a = a
self.b = b
class B(A):
def __init__(self, parent_instance, c):
# initiate the parent class with all the arguments coming from
# parent class __dict__
super().__init__(*tuple(parent_instance.__dict__.values()))
self.c = c
a_instance = A(1, 2)
b_instance = B(a_instance, 7)
print(b_instance.a + b_instance.b + b_instance.c)
>> 10
Or you could have a sperate function for this:
def class_converter(convert_to, parent_instance):
return convert_to(*tuple(parent_instance.__dict__.values()))
class B(A):
def __init__(self, *args):
super().__init__(*args)
self.c = 5
But using the 2nd method, I wasn't able to figure out how to pass additional values

Categories