Override inner class - python

Lets have an example
class A:
class B:
def f(self):
return 1
def a(self):
return A.B().f()
def b(self):
return self.B().f()
class C(A):
class B(A.B):
def f(self):
return 2
print(A().a())
print(A().b())
print(C().a())
print(C().b())
will produce
1
1
1
2
I want to do something, that it produces
1
1
2
2
How can I override class A, so that both methods, a and b returns 2?
I am working with generated code with antlr. What I want to do, is for example to override __str__() methods to have some kind of better information. It keeps generating code like MyLanguageParser.RootContext() instead of self.RootContext(), and now, what I want to override anything I need to cope methods code, where classes are being called.
Do you have any solutions? I know I am not the best with Python yet.
Maybe it is not possible and solution is to change generated code, but what I heard it is very bad idea.
Edit:
Class A is generated and is immutable
What I have thought is something like
A.B = C.B
print(A().a())
print(A().b())
print(C().a())
print(C().b())
will generate
2
2
2
2
I do not know if it is legal. Actually I will not use A class, but rest of generated code can use it. I do not know if it is safe.
Edit 2: Corrected error with lack of self

Possibly:
class A:
class B:
def f(self):
return 1
def a(self):
# `type(self)` here instead of `A`
# to get actual `C` class instead of `A`
# when `a()` calls for `C()`
return type(self).B().f()
def b(self):
return self.B().f()
class C(A):
class B(A.B):
def f(self):
return 2
Or without modifing A:
class A:
class B:
def f(self):
return 1
def a(self):
return A.B().f()
def b(self):
return self.B().f()
class C(A):
class B(A.B):
def f(self):
return 2
def a(self): # reimplement
return type(self).B().f()
Or somehow trying to rewrite A dynamically to avoid rewriting a's code:
class A:
class B:
def f(self):
return 1
def a(self):
return A.B().f()
def b(self):
return self.B().f()
class C(A):
class B(A.B):
def f(self):
return 2
def a(self):
tmp, globals()['A'] = A, type(self)
try:
return super().a()
finally:
globals()['A'] = tmp
Note, this might be bad idea. I would think if there's better way.

Related

Make variable common to all subclasses

I want a class temp with a variable a, and its two subclasses c1 and c2. If a is changed in c1, it should also be reflected in c2 and vice-versa. For this, I tried:
class temp(ABC):
a=1
def f(self):
pass
class c1(temp):
def f(self):
print(self.a)
class c2(temp):
def f(self):
print(self.a)
o1=c1()
o2=c2()
o1.f()
o2.f()
o1.a+=1
o1.f()
o2.f()
It gives me output:
1
1
2
1
whereas I want it to be
1
1
2
2
I also tried super.a instead of self.a, but it gives me an error. How can I achieve the desired target? Thanks...
Rather than incrementing o1.a, you need to increment the static variable itself.
Ie temp.a += 1
class temp():
a=1
def f(self):
pass
class c1(temp):
def f(self):
print(self.a)
class c2(temp):
def f(self):
print(self.a)
o1=c1()
o2=c2()
o1.f()
o2.f()
temp.a+=1
o1.f()
o2.f()
>>> 1
1
2
2

How to dynamically inherit at initialization time?

I have the following class structure:
class Base:
def z(self):
raise NotImplementedError()
class A(Base):
def z(self):
self._x()
return self._z()
def _x(self):
# do stuff
def _a(self):
raise NotImplementedError()
class B(Base)
def z(self):
self._x()
return self._z()
def _x(self):
# do stuff
def _z(self):
raise NotImplementedError()
class C(A):
def _z(self):
print(5)
class D(B):
def _z(self):
print(5)
The implementation of C(A) and D(B) is exactly the same and does not really care which class it inherits from. The conceptual difference is only in A and B (and these need to be kept as separate classes). Instead of writing separate definitions for C and D, I want to be able to dynamically inherit from A or B based on an argument provided at time of creating an instance of C/D (eventually C and D must be the same name).
It seems that metaclasses might work, but I am not sure how to pass an __init__ argument to the metaclass __new__ (and whether this will actually work). I would really prefer a solution which resolves the problem inside the class.
Have you considered using composition instead of inheritance? It seems like it is much more suitable for this use case. See the bottom of the answer for details.
Anyway,
class C(A): ......... class C(B): ..... is not even valid, and will result with only class C(B) getting defined.
I'm not sure a metaclass will be able to help you here. I believe the best way would be to use type but I'd love to be corrected.
A solution using type (and probably misusing locals() but that's not the point here)
class A:
def __init__(self):
print('Inherited from A')
class B:
def __init__(self):
print('Inherited from B')
class_to_inherit = input() # 'A' or 'B"
C = type('C', (locals()[class_to_inherit],), {})
C()
'A' or 'B'
>> A
Inherited from A
'A' or 'B'
>> B
Inherited from B
Composition
Tracking back to the question in the beginning of my answer, you state yourself that the implementation of both "C(A)" and "C(B)" is identical and they don't actually care about A or B. It seems more correct to me to use composition. Then you can do something along the lines of:
class A: pass
class B: pass
class C:
def __init__(self, obj): # obj is either A or B instance, or A or B themselves
self.obj = obj # or self.obj = obj() if obj is A or B themselves
c = C(A()) # or c = C(A)
In case C should expose the same API as A or B, C can overwrite __getattr__:
class A:
def foo(self):
print('foo')
class C:
def __init__(self, obj):
self.obj = obj
def __getattr__(self, item):
return getattr(self.obj, item)
C(A()).foo()
# foo

Python: Inheriting methods of a parent class without being a child of the class

I can't seem to find information regarding what I'm trying to do, so I'm afraid the answer is "you can't do it" or "that's bad practice." But, here it goes:
Given the following:
Class A(object):
def __init__(self):
pass
def methoda(self):
return 1
Class C(object):
def __init__(self):
pass
def methodc(self):
return 2
import A, C
Class B(object):
def __init__(self, classC):
A.__init__(self)
if classC:
C.__init__(self)
def methodb(self):
return 2
Obviously, running:
b = A()
b.methoda()
Is going to crash with an error:
Unbound method __init()___ must be called with A class as first argument (got B instance instead)
However, I am basically looking for a way to make this work. My motivation:
There are classes (maybe in the future) that will duplicate a certain group of methods (say some fancy conversions). In an effort to reduce code, I'd like for the future classes to inherit the methods; but for legacy reasons, I don't want B to inherit C.
A couple solutions:
Don't use special methods directly:
class A(object):
def __init__(self):
self._init(self)
#staticmethod
def _init(self):
...actual initialization code here...
def methoda(self):
return 1
class C(object):
def __init__(self):
self._init(self)
#staticmethod
def _init(self):
...actual initialization code here...
def methodc(self):
return 2
import A, C
class B(object):
def __init__(self, classC):
A._init(self)
if classC:
C._init(self)
def methodb(self):
return 2
Or silly hacks involving copying from initialized objects:
import A, C
class B(object):
def __init__(self, classC):
vars(self).update(vars(A()))
if classC:
vars(self).update(vars(C()))
def methodb(self):
return 2
Note that none of these solutions will give access to methods from A or C on instances of B. That's just ugly. If you really need inheritance, use inheritance, don't do terrible things trying to simulate it poorly.
I ended up just inheriting multiple classes. It's not exactly the way I wanted it done, but it's cleaner and easier for the IDE to follow
Class A(object):
def __init__(self):
super(A, self).__init__()
pass
def methoda(self):
return 1
Class C(object):
def __init__(self):
super(C, self).__init__()
def _C_init(self):
# some init stuff
pass
def methodc(self):
return 1
Class B(A, C):
def __init__(self, use_C):
super(B, self).__init__()
if use_C:
self._C_init()
def methodb(self):
return 2

Python : Set method attribute from within method

I am trying to make a python decorator that adds attributes to methods of a class so that I can access and modify those attributes from within the method itself. The decorator code is
from types import MethodType
class attribute(object):
def __init__(self, **attributes):
self.attributes = attributes
def __call__(self, function):
class override(object):
def __init__(self, function, attributes):
self.__function = function
for att in attributes:
setattr(self, att, attributes[att])
def __call__(self, *args, **kwargs):
return self.__function(*args, **kwargs)
def __get__(self, instance, owner):
return MethodType(self, instance, owner)
retval = override(function, self.attributes)
return retval
I tried this decorator on the toy example that follows.
class bar(object):
#attribute(a=2)
def foo(self):
print self.foo.a
self.foo.a = 1
Though I am able to access the value of attribute 'a' from within foo(), I can't set it to another value. Indeed, when I call bar().foo(), I get the following AttributeError.
AttributeError: 'instancemethod' object has no attribute 'a'
Why is this? More importantly how can I achieve my goal?
Edit
Just to be more specific, I am trying to find a simple way to implement static variable that are located within class methods. Continuing from the example above, I would like instantiate b = bar(), call both foo() and doo() methods and then access b.foo.a and b.doo.a later on.
class bar(object):
#attribute(a=2)
def foo(self):
self.foo.a = 1
#attribute(a=4)
def doo(self):
self.foo.a = 3
The best way to do this is to not do it at all.
First of all, there is no need for an attribute decorator; you can just assign it yourself:
class bar(object):
def foo(self):
print self.foo.a
self.foo.a = 1
foo.a = 2
However, this still encounters the same errors. You need to do:
self.foo.__dict__['a'] = 1
You can instead use a metaclass...but that gets messy quickly.
On the other hand, there are cleaner alternatives.
You can use defaults:
def foo(self, a):
print a[0]
a[0] = 2
foo.func_defaults = foo.func_defaults[:-1] + ([2],)
Of course, my preferred way is to avoid this altogether and use a callable class ("functor" in C++ words):
class bar(object):
def __init__(self):
self.foo = self.foo_method(self)
class foo_method(object):
def __init__(self, bar):
self.bar = bar
self.a = 2
def __call__(self):
print self.a
self.a = 1
Or just use classic class attributes:
class bar(object):
def __init__(self):
self.a = 1
def foo(self):
print self.a
self.a = 2
If it's that you want to hide a from derived classes, use whatever private attributes are called in Python terminology:
class bar(object):
def __init__(self):
self.__a = 1 # this will be implicitly mangled as __bar__a or similar
def foo(self):
print self.__a
self.__a = 2
EDIT: You want static attributes?
class bar(object):
a = 1
def foo(self):
print self.a
self.a = 2
EDIT 2: If you want static attributes visible to only the current function, you can use PyExt's modify_function:
import pyext
def wrap_mod(*args, **kw):
def inner(f):
return pyext.modify_function(f, *args, **kw)
return inner
class bar(object):
#wrap_mod(globals={'a': [1]})
def foo(self):
print a[0]
a[0] = 2
It's slightly ugly and hackish. But it works.
My recommendation would be just to use double underscores:
class bar(object):
__a = 1
def foo(self):
print self.__a
self.__a = 2
Although this is visible to the other functions, it's invisible to anything else (actually, it's there, but it's mangled).
FINAL EDIT: Use this:
import pyext
def wrap_mod(*args, **kw):
def inner(f):
return pyext.modify_function(f, *args, **kw)
return inner
class bar(object):
#wrap_mod(globals={'a': [1]})
def foo(self):
print a[0]
a[0] = 2
foo.a = foo.func_globals['a']
b = bar()
b.foo() # prints 1
b.foo() # prints 2
# external access
b.foo.a[0] = 77
b.foo() # prints 77
While You can accomplish Your goal by replacing self.foo.a = 1 with self.foo.__dict__['a'] = 1 it is generally not recommended.
If you are using Python2 - (and not Python3) - whenever you retrieve a method from an instance, a new instance method object is created which is a wrapper to the original function defined in the class body.
The instance method is a rather transparent proxy to the function - you can retrieve the function's attributes through it, but not set them - that is why setting an item in self.foo.__dict__ works.
Alternatively you can reach the function object itself using: self.foo.im_func - the im_func attribute of instance methods point the underlying function.
Based on other contributors's answers, I came up with the following workaround. First, wrap a dictionnary in a class resolving non-existant attributes to the wrapped dictionnary such as the following code.
class DictWrapper(object):
def __init__(self, d):
self.d = d
def __getattr__(self, key):
return self.d[key]
Credits to Lucas Jones for this code.
Then implement a addstatic decorator with a statics attribute that will store the static attributes.
class addstatic(object):
def __init__(self, **statics):
self.statics = statics
def __call__(self, function):
class override(object):
def __init__(self, function, statics):
self.__function = function
self.statics = DictWrapper(statics)
def __call__(self, *args, **kwargs):
return self.__function(*args, **kwargs)
def __get__(self, instance, objtype):
from types import MethodType
return MethodType(self, instance)
retval = override(function, self.statics)
return retval
The following code is an example of how the addstatic decorator can be used on methods.
class bar(object):
#attribute(a=2, b=3)
def foo(self):
self.foo.statics.a = 1
self.foo.statics.b = 2
Then, playing with an instance of the bar class yields :
>>> b = bar()
>>> b.foo.statics.a
2
>>> b.foo.statics.b
3
>>> b.foo()
>>> b.foo.statics.a
3
>>> b.foo.statics.b
5
The reason for using this statics dictionnary follows jsbueno's answer which suggest that what I want would require overloading the dot operator of and instance method wrapping the foo function, which I am not sure is possible. Of course, the method's attribute could be set in self.foo.__dict__, but since it not recommended (as suggested by brainovergrow), I came up with this workaround. I am not certain this would be recommended either and I guess it is up for comments.

Access to the methods of the class from which it was instantiated another class

I'm trying to access the methods of the class from which it was instantiated another class, I mean, accessing to the "parent" instance without creating a new instance of it.
class A():
def __init__(self):
...
b_instance = B()
...
class B():
def __init__(self):
...
def function1(self):
...
def function2(self):
C().run() # I need to use class C functionalities
...
class C():
def __init__(self):
...
def run(self):
classB.function1() #I can't access to these methods without instantiating again class B
# I have to execute:
>>> a = A()
>>> a.b_instance.function2()
Sorry if I have not explained well, is a bit confusing. If you need any clarification do not hesitate to ask.
EDIT.
In class C a specific handling of the execution of class B methods is done. Is not possible to instanciate again inside C because class B contains the initialization of hardware.
It's still not clear what exactly you're trying to achieve, but here's one fix:
class A():
def __init__(self):
...
b_instance = B()
...
class B():
def __init__(self):
...
def function1(self):
...
def function2(self):
C().run(self) # pass class B instance to C instance run method
...
class C():
def __init__(self):
...
def run(self, classB): # note additional parameter
classB.function1()
However, note that this represents a very high level of coupling between your various classes, which seems suspicious to me and may indicate a deeper flaw in your design.
This can access the class methods from other classes.
use instance method, class methods and static methods, if you are using various types of functins.
class A():
def __init__(self):
print 'in __init__'
self.b_instance = B() # making an instance of class
#self.b_instance.function2()
class B():
def __init__(self):
print 'in __init__, B'
#staticmethod
def function1():
print 'func1'
def function2(self):
C().run() # I need to use class C functionalities
# if you trying to access `run` method of `class C` make
# it instance bound method"""
class C():
def __init__(self):
pass
def run(self):
print 'in run'
B.function1() #I can't access to these methods without instantiating again class B
#you are passing class instance as `B` while calling function1
# so make it either classmethod `#classmethod` or `static method`
# I have to execute:
a = A()
a.b_instance.function2() # calling b_instance variable of class A

Categories

Resources