Python using methods from other classes - python

If I have two classes, and one of them has a function that I want to use in my other class, what do I use so that I don't have to rewrite my function?

There are two options:
instanciate an object in your class, then call the desired method on it
use #classmethod to turn a function into a class method
Example:
class A(object):
def a1(self):
""" This is an instance method. """
print "Hello from an instance of A"
#classmethod
def a2(cls):
""" This a classmethod. """
print "Hello from class A"
class B(object):
def b1(self):
print A().a1() # => prints 'Hello from an instance of A'
print A.a2() # => 'Hello from class A'
Or use inheritance, if appropriate:
class A(object):
def a1(self):
print "Hello from Superclass"
class B(A):
pass
B().a1() # => prints 'Hello from Superclass'

There are several approaches:
Inheritance
Delegation
Super-sneaky delegation
The following examples use each for sharing a function that prints a member.
Inheritance
class Common(object):
def __init__(self,x):
self.x = x
def sharedMethod(self):
print self.x
class Alpha(Common):
def __init__(self):
Common.__init__(self,"Alpha")
class Bravo(Common):
def __init__(self):
Common.__init__(self,"Bravo")
Delegation
class Common(object):
def __init__(self,x):
self.x = x
def sharedMethod(self):
print self.x
class Alpha(object):
def __init__(self):
self.common = Common("Alpha")
def sharedMethod(self):
self.common.sharedMethod()
class Bravo(object):
def __init__(self):
self.common = Common("Bravo")
def sharedMethod(self):
self.common.sharedMethod()
Super-sneaky Delegation
This solution is based off of the fact that there is nothing special about Python member functions; you can use any function or callable object so long as the first parameter is interpreted as the instance of the class.
def commonPrint(self):
print self.x
class Alpha(object):
def __init__(self):
self.x = "Alpha"
sharedMethod = commonPrint
class Bravo(object):
def __init__(self):
self.x = "Bravo"
sharedMethod = commonPrint
Or, a similarly sneaky way of achieving delegation is to use a callable object:
class Printable(object):
def __init__(self,x):
self.x = x
def __call__(self):
print self.x
class Alpha(object):
def __init__(self):
self.sharedMethod = Printable("Alpha")
class Bravo(object):
def __init__(self):
self.sharedMethod = Printable("Bravo")

you create a class from which both classes inherit.
There is multiple inheritance, so if they already have a parent it's not a problem.
class master ():
def stuff (self):
pass
class first (master):
pass
class second (master):
pass
ichi=first()
ni=second()
ichi.stuff()
ni.stuff()

Related

How can I dynamically refer to a child class from the super class in Python?

Consider this situation:
class Foo(ABC):
#abstractmethod
def some_method(self):
return
class Bar(Foo):
def some_method(self, param):
# do stuff
return
class Baz(Foo):
def some_method(self, param):
# do stuff differently
return
def do_something_with_obj(some_obj: Foo):
some_param = 'stuff'
some_obj.some_method(some_param)
def main(cond):
if cond:
obj = Bar()
else:
obj = Baz()
do_something_with_obj(obj)
I get an Expected 0 positional arguments error when I try to call some_method() under the do_something_with_obj() method. Of course, this is because I'm essentially calling the abstract method. My question is, how can I dynamically refer to the child class method since I have to choose the right child class based on some condition beforehand?

Create child class object using parent class instance

lets say we have class A and it has one instance - x. How to make a child class of class A where I would be able to pass x as an argument and get all its parameters and pass it to child class object. precisely speaking I want to do something like this.
class A:
def __init__(self, parameter1, parameter2):
self.parameter1 = parameter1
self.parameter2 = parameter2
class B(A):
def __init__(self, Ainstance, someParameter):
super().__init__(**Ainstance.__dict__)
self.someParameter = someParameter
x = A(parameter1='1', parameter2='2')
x = B(x, someParameter='3')
print(x.parameter1)
print(x.parameter2)
print(x.someParameter)
the goal is to create a class where I would be able to get all the parameters of parent class object, and add my own attributes. The problem in the code above is I won't be able to do that with all classes because not all of them has __dict__ attribute.
I have this example code which I use to remind myself how to construct a proxy.
#soProxyPattern
class Example:
def __init__(self):
self.tag_name = 'name'
def foo(self):
return 'foo'
def bar(self, param):
return param
class Container:
def __init__(self, contained):
self.contained = contained
self.user_name = 'username'
def zoo(self):
return 0
def __getattr__(self, item):
if hasattr(self.contained, item):
return getattr(self.contained,item)
#raise item
c = Container(Example())
print(c.zoo())
print(c.foo())
print(c.bar('BAR'))
print(c.tag_name)
print(c.user_name)
The output is:
0
foo
BAR
name
username
This shows that Container can have its own attributes (methods or variables) which you can access over and above all of the attributes of the contained instance.
Instead of dict you could use the dir and getattr like this:
class A:
def __init__(self, parameter1, parameter2):
self.parameter1 = parameter1
self.parameter2 = parameter2
class B(A):
def __init__(self, Ainstance, someParameter):
parameters = {param: getattr(Ainstance, param) for param in dir(Ainstance) if not param.startswith("__")}
super().__init__(**parameters)
self.someParameter = someParameter
For a more detailed explanation see: Get all object attributes in Python?

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

Selective Inheritance Python

I am making a python program which is using classes, I want one class to only selectively inherit from another e.g:
class X(object):
def __init__(self):
self.hello = 'hello'
class Y(object):
def __init__(self):
self.moo = 'moo'
class Z():
def __init__(self, mode):
if mode == 'Y':
# Class will now Inherit from Y
elif mode == 'X':
# Class will now Inherit for X
How can I do this without making another class?
In Python classes can be created at run-time:
class X(object):
def __init__(self):
self.hello = 'hello'
class Y(object):
def __init__(self):
self.moo = 'moo'
def create_class_Z(mode):
base_class = globals()[mode]
class Z(base_class):
def __init__(self):
base_class.__init__(self)
return Z
ZX = create_class_Z('X')
zx = ZX()
print(zx.hello)
ZY = create_class_Z('Y')
zy = ZY()
print(zy.moo)
You can do this by overriding __new__ and changing the cls passed in (you're creating a new type by appending X or Y as a base class):
class X(object):
def __init__(self):
self.hello = 'hello'
class Y(object):
def __init__(self):
self.moo = 'moo'
class Z(object):
def __new__(cls, mode):
mixin = {'X': X, 'Y': Y}[mode]
cls = type(cls.__name__ + '+' + mixin.__name__, (cls, mixin), {})
return super(Z, cls).__new__(cls)
def __init__(self, mode, *args, **kwargs):
super(Z, self).__init__(*args, **kwargs)
Note that you need to bypass Z.__new__ using super to avoid infinite recursion; this is the standard pattern for __new__ special override methods.
I think you'd better define two members within Z,one is a class instance of X,another is a instance of Y.You can get the associated information stored in these instances while use different mode.
A solution using type:
class _Z(): pass #rename your class Z to this
def Z(mode): #this function acts as the constructor for class Z
classes = {'X': X, 'Y': Y, 'Foo': Bar} #map the mode argument to the base cls
#create a new type with base classes Z and the class determined by mode
cls = type('Z', (_Z, classes[mode]), {})
#instantiate the class and return the instance
return cls()

confusion over inherited objects in abstract base class

Im a bit confused about inherited instance variables in ABCs. I have written an example to show my confusion. Class A needs a list which class B inherits but it must be an instance object rather than a class object. However class B also needs its own instance variable local. Can anyone set me straight?
#!python
from abc import ABCMeta, abstractmethod, abstractproperty
import unittest
class A(object):
__metaclass__ = ABCMeta
_internal = ['initialized']
#property
def internal(self):
return self._internal
def get_a(self):
return self._internal
#abstractmethod
def set_a(self, value):
pass
class B(A):
def __init__(self):
self.local = 'OK'
def get_local(self):
return self.local
def set_a(self, value):
self._internal.append(value)
class TestCase(unittest.TestCase):
def test_implementation(self):
self.assertEqual(['initialized'], B().get_a() ) # this passes but for wrong reason
b_used = B().set_a('used')
b_unused = B()
print "b_used.get_a() should return ['initialized','used']"
print "b_unused.get_a() should return ['initialized']"
print "b_used.get_local() should equal b_unused.get_local() = 'OK'"
self.assertEqual(['initialized'], b_unused.get_a()) # >> fails with ['initialized'] =! ['initialized', 'used']
self.assertNotEqual(b_unused.get_a(), b_used.get_a())
if __name__ == "__main__":
unittest.main()
The problem is that _internal is a class obj of class A. I need it to be an instance object of class B.
Thanks In advance
You should initialize instance attributes in __init__() and call the base class __init__() in B:
class A(object):
__metaclass__ = ABCMeta
def __init__(self):
self._internal = ['initialized']
...
class B(A):
def __init__(self):
A.__init__(self)
self.local = 'OK'
...
You should also fix your unit test:
class TestCase(unittest.TestCase):
def test_implementation(self):
self.assertEqual(['initialized'], B().get_a() ) # this passes but for wrong reason
b_used = B()
b_used.set_a('used')
b_unused = B()
...
Instance attributes should be defined in a method, eg __init__, by setting them on self.

Categories

Resources