Let's say I have this code:
class class1(object):
def __init__(self):
#don't worry about this
def parse(self, array):
# do something with array
class class2(object):
def __init__(self):
#don't worry about this
def parse(self, array):
# do something else with array
I want to be able to call class1's parse from class2 and vice-versa. I know with c++ this can be done quite easily by doing
class1::parse(array)
How would I do the equivalent in python?
It sounds like you want a static method:
class class1(object):
#staticmethod
def parse(array):
...
Note that in such cases you leave off the usually-required self parameter, because parse is not a function called on a particular instance of class1.
On the other hand, if you want a method which is still tied to its owner class, you can write a class method, where the first argument is actually the class object:
class class1(object):
#classmethod
def parse(cls, array):
...
Related
I am experimenting with python object orientated programming. Of course I learned about inheritence and so on, but this question is very specific and I couldn't find the answer anywhere yet.
Let's say we have a class class mainClass:. In this class there is a function def func(self):. And within this function func() I want to use two custom classes. Can I and how can I use the first custom class within the second one? (Here's a example)
class custom1:
def func1(self):
#do something
class custom2:
def func2(self):
#call function func1 from class custom1 without creating another instance
class mainClass:
def func(self):
obj1 = custom1()
obj2 = custom2()
obj2.func2()
Like I said I don't want to create a second instance of custom1 within custom2. Only the one in mainClass.
Thanks for your answers :)
what about passing it via the constructor of the first class?
class custom1:
def func1(self):
#do something
class custom2:
def __init__(self, obj1):
self._obj1 = obj1
def func2(self):
self._obj1.func1()
class mainClass:
def func(self):
obj1 = custom1()
obj2 = custom2(obj1)
obj2.func2()
I have a class called resources and I have defined one method called get_connect. I want to use the data of which get_connect returns to the other classes. I need at least three classes and I use the data of get_connect and I have to parse that data. To implement this I have written the code below
class resources:
#staticmethod
def get_connect():
return 1 + 2
class Source1(resources):
def __init__(self):
self.response = resources.get_connect()
def get__details1(self):
print(self.response)
class Source2(resources):
def __init__(self):
self.response = resources.get_connect()
def get_details2(self):
print(self.response)
class Source3(resources):
def __init__(self):
self.response = resources.get_connect()
def get__detail3(self):
print(self.response)
source1 = Source1()
source2 = Source2()
source3 = Source3()
source1.get__details1()
source2.get_details2()
source3.get__detail3()
But the problem with the code is for every class in init method I am calling the get_connect method. I don't want to repeat the code. I need help for avoiding redundancy which I have asked below
Is there any way I can call get_connect in one place and use it for other classes maybe a decorator or anything? if yes how can I?
While creating objects also I am calling each class and calling each method every time. is there a way to use any design pattern here?
If anyone helps me with these oops concepts it will be useful.
First of all, is there any reason why you are using get_connect method as static?
Because what you can do here is declare it in the parent class:
class resources:
def __init__(self):
self.response = self.get_connect()
def get_connect(self):
return 1 + 2
This way you do not need to define the __init__ method on every class, as it will be automatically inherited from the parent.
Regarding the second question, it really depends on the context, but you can use a strategy pattern in order to retrieve the class that you require to call. For this rename the method of get details into the same for each of the classes, as basically they're used for the same purpose, but changed on the context of the class implementation:
class Source1(resources):
def get_details(self):
print(self.response)
class Source2(resources):
def get_details(self):
print(self.response)
class Source3(resources):
def get_details(self):
print(self.response)
classes = {
"source_1": Source1,
"source_2": Source2,
"source_3": Source3
}
source_class = classes["source_1"]
source = source_class()
source.get_details()
Hope this helped!
I'm looking for an equivalent to the static { ... } block in Java that can be used in Python classes. Specifically, I want to be able to access static resources like the arguments of the class constructor and store them in a field of the class, like so:
class A:
constructor_args = A.__init__.__code__.co_varnames
def __init__(self, foo=0, bar=1):
...
This example doesn't work, because class A is not yet initialized when I call A.__init__.__code__.co_varnames.
My current workaround is to alter the static field after the class has been created like so:
class A:
constructor_args = ...
def __init__(self, foo=0, bar=1):
...
constructor_args = A.__init__.__code__.co_varnames
But this solution is rather ugly because I change a static field of a class outside of the class context and if the class contains a lot of code, it's easy to miss out on what is going on here.
So basically I need a way to call a function right after the class has been initialized, and I want to define this function inside of the class.
You will have to at least define the __init__ method first, but you can access its properties immediately after:
class Foo:
def __init__(self, bar, baz):
pass
constructor_args = __init__.__code__.co_varnames
Inside the class block code executes inside its own namespace, so __init__ is directly accessible as __init__.
Here is a simple approach that postpones execution of code that needs the finished class by moving it inside a function defined inside the class body. To have the function called and deleted after use we define a simple decorator:
import inspect
def finalizing(cls):
cls.__finalize__(cls)
del cls.__finalize__
return cls
#finalizing
class example:
def __finalize__(me):
me.constructor_args = list(inspect.signature(me.__init__).parameters)
def __init__(self, x):
pass
example.constructor_args
# ['self', 'x']
You could use a class decorator:
def store_constructor_args(cls):
cls.constructor_args = cls.__init__.__code__.co_varnames
return cls
#store_constructor_args
class A:
def __init__(self, foo=0, bar=1):
x = 10
print(A.constructor_args)
# ('self', 'foo', 'bar', 'x')
#store_constructor_args
class A:
is equivalent to
class A:
...
A = store_constructor_args(A)
I have a python abstract base class as follows:
class Node(object):
"""
All concrete node classes should inherit from this
"""
__metaclass__ = ABCMeta
def __init__(self, name):
self.name = name
self.inputs = dict()
def add_input(self, key, value=None, d=None):
self.inputs[key] = (d, value)
def bind_input(self):
print "Binding inputs"
#abstractmethod
def run(self):
pass
Now, various derived classes will inherit from this node class and override the run method. It is always the case that bind_input() must be the first thing that should be called in the run method. Currently, for all derived classes the developer has to make sure to first call self.bind_input(). This is not a huge problem per se but out of curiosity is it possible to ensure this somehow from the base class itself that bind_input is called before executing the child object's run?
The usual object-oriented approach is this:
def run(self):
self.bind_input()
return self.do_run()
#abstractmethod
def do_run(self):
pass # override this method
Have your subclasses override the inner method, instead of the outer one.
class Something(object):
our_random = Something.random_thing
#staticmethod
def random_thing():
return 4
Of course, this doesn't work, becauese Something doesn't exist when I attempt to call its method. Nor does this:
class Something(object):
our_random = random_thing
#staticmethod
def random_thing():
return 4
I've "solved" this by Just placing random_thing()'s definition above the class, but I find this messy.
Call it in the .__init__() initializer then:
class Something(object):
def __init__(self):
self.our_random = Something.random_thing()
or call the static method after you defined it, but are still defining the class; because it is a static method, you'd have to access it through the __func__ attribute:
class Something(object):
#staticmethod
def random_thing():
return 4
our_random = random_thing.__func__()
If you didn't mean to call it, just create a copy of the method with a different name, just do so after you defined it:
class Something(object):
#staticmethod
def random_thing():
return 4
our_random = random_thing # our_random as an alias for random_thing
The class body is executed as a function, with the local namespace of the function then forming the class attributes. So, like a function, if you want to refer to other objects you need to make sure they are defined first.
class Something(object):
#staticmethod
def random_thing():
return 4
our_random = random_thing
Class definitions create a namespace, so you can refer to other names (class attributes) within the class body without needing to access them through the class.