Python: set class method as class attribut - python

The following seems not to be valid in python 3:
class A:
callback = A.callback_function
def callback_function(self):
pass
You'll get an error saying type 'A' is not defined. Is it because 'A' cannot be refered to in it self? Is there anyway I can achieve this type of functionality?
What I'm trying to do is something like this: I have a base class:
class Base:
callback = Base.ignore
def ignore(self):
pass
def some_other_function(self):
self.callback()
In a subclass I'd like to set another callback function:
class Derived(Base):
callback = Derived.special_function
def special_function(self):
do_stuff()

Well, you can just name your function callback, and it'll be just the same, but if you really insist on this way:
class A:
def callback_function(self): pass
callback = callback_function

Related

Can you override a function from a class outside of a class in Python

Can you override a function from a class, like:
class A:
def func():
print("Out of A")
classA = A
# Is something like this possible
def classA.func():
print("Overrided!")
Wanted Output:
Overrided
I googled "python override function", "python override function from class" and so on but couldnt find anything that fits. I found just how to override the parent function.
You most likely shouldn't do this. If you want to change a single part of some class, make a new class that inherits from it and reimplement the parts you want changed:
class A:
#staticmethod
def func():
print("Out of A")
classA = A
class B(A):
#staticmethod
def func():
print("Overridden!")
A.func()
B.func()

Calling a function From a class with self arguments

class Login(QMainWindow):
def __init__(self):
super(Login,self).__init__()
loadUi("gui.ui",self)
self.startButton.clicked.connect(self.start)
self.stopButton.clicked.connect(self.stop)
def start(self):
self.lcdNumber_4.display(0)
I'm trying to call start from outside the class
I have tried:
login = Login()
login.start()
I think it has to do with the QMainWindow argument it takes
class c(self):
is nonsensical. It says the new class c inherits from whatever is stored in some outside variable named self, which probably doesn't exist (triggering a NameError). Just change it to:
class c:
and it will work as written.

Calling subsclass #classmethod from parent class

I'm trying to do the following:
class A:
#classmethod
def test_function(cls, message):
cls.__get_the_function()
class B(A):
#classmethod
def __get_the_function(cls):
return print("BBBB")
class C(A):
#classmethod
def __get_the_function(cls):
return print("CCCC")
however when I call:
B.test_function("Test")
I get the following:
AttributeError: type object 'B' has no attribute '_A__get_the_function'
I want class A to __get_the_function from the subclass (either class B or C depends on which one I use), but it looks like it is trying to look for it in itself.
NOTE: I'm using Python 3.8.2
__-prefixed names are handled specially during class creation. The name is replaced when the function is defined by a mangled name, as if you had defined the function as
#classmethod
def test_function(cls, message):
cls._A__get_the_function()
in the first place.
This is done to explicitly provide a way to hide a name from a subclass. Since you want to override the name, __get_the_function isn't an appropriate name; use an ordinary _-prefixed name if you want to mark it as private:
class A:
#classmethod
def test_function(cls, message):
cls._get_the_function()
# Define *something*, since test_function assumes it
# will exist. It doesn't have to *do* anything, though,
# until you override it.
#classmethod
def _get_the_function(cls):
pass

passing a class to another class

Here's my problem statement:
I've an extractor class which calls a ConfigManager class and passes a type as an argument. Based on the type, ConfigManager resolves the class that needs to be called.
At this point, ConfigManager has a reference to the class.
However ConfigManager needs to pass this class back to the extractor.
ConfigManager is a helper class which the Extractor will call to get type specific class.
How do I make the ConfigManager pass the class to Extractor?
I'm new to python and any help is much appreciated.
Extractor -> ConfigManager -> AbstractLoader| -> Metric1Loader
Extractor class calls ConfigManager. ConfigManager gets Metric1Loader class and needs to pass it to Extractor.
ConfigManager should pass class reference of Metric1Loader back to Extractor.
To me, your requirement sounds like a problem which can be solved by factory design pattern.
Here's an example which can be used as a reference.
class AbstractLoader:
def __init__(self):
pass
class Metric1Loader(AbstractLoader):
def __init__(self):
print('Metric1Loader')
class Metric2Loader(AbstractLoader):
def __init__(self):
print('Metric2Loader')
class Factory:
#staticmethod
def make_class(target_class):
# This will instantiate object of type determined from target_class string
return globals()[target_class]()
def extractor():
types = ['Metric1Loader', 'Metric2Loader']
for type in types:
obj = Factory.make_class(type)
if __name__ == '__main__':
extractor()
# STDOUT:
# Metric1Loader
# Metric2Loader
perhaps create a method that returns the data to the object that needs it?
def ConfigManager:
def resolveClass(self, name):
return obj
def Extractor:
def doSomething(self):
configManager = ConfigManager()
resolvedClass = configManager.resolveClass("name")

How to convert (inherit) parent to child class?

I would like to know how to convert parent object that was return by some function to child class.
class A(object):
def __init__():
pass
class B(A):
def functionIneed():
pass
i = module.getObject() # i will get object that is class A
j = B(i) # this will return exception
j.functionIneed()
I cannot change class A. If I could I would implement functionIneed to class A, but it is impossible because of structure of code.
Python does not support "casting". You will need to write B.__init__() so that it can take an A and initialize itself appropriately.
I have a strong suspicion, nay, conviction, that there is something horribly wrong with your program design that it requires you to do this. In Python, unlike Java, very few problems require classes to solve. If there's a function you need, simply define it:
def function_i_need(a):
"""parameter a: an instance of A"""
pass # do something with 'a'
However, if I cannot dissuade you from making your function a method of the class, you can change an instance's class by setting its __class__ attribute:
>>> class A(object):
... def __init__(self):
... pass
...
>>> class B(A):
... def functionIneed(self):
... print 'functionIneed'
...
>>> a = A()
>>> a.functionIneed()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'A' object has no attribute 'functionIneed'
>>> a.__class__ = B
>>> a.functionIneed()
functionIneed
This will work as long as B has no __init__ method, since, obviously, that __init__ will never be called.
You said you want to implement something like this:
class B(A):
def functionIneed():
pass
But really what you would be making is something more like this (unless you had intended on making a class or static method in the first place):
class B(A):
def functionIneed(self):
pass
Then you can call B.functionIneed(instance_of_A). (This is one of the advantages of having to pass self explicitly to methods.)
You did not correctly define your classes.
Should be like this:
class A(object):
def __init__(self):
pass
class B(A):
def __init__(self):
super(B,self).__init__()
def functionIneed(self):
pass
Then you can
j=B()
j.fuctionIneed()
as expected
You forgot to refer to the ins
Just thinking outside the box:
Instead of a new class with the function you want, how about just adding the function to the class or instance you already have?
There is a good description of this in
Adding a Method to an Existing Object Instance
How about:
i = module.getObject() # i will get object that is class A
try:
i.functionIneed()
except AttributeError:
# handle case when u have a bad object
Read up on duck typing.

Categories