I am trying to create a class in the superclass
I have a superclass in SuperTest.py:
class SuperTest():
def func(self):
return Test2()
And test.py
from SuperTest import *
class Test(SuperTest):
def create(self):
return self.func()
class Test2(SuperTest):
pass
test = Test()
print test.create()
Then I have an error NameError: global name 'Test2' is not defined.
Is it possible to do that? How to handle the scope? As I know I can't mutually import the classes recursively.
I will be getting some class names in the superclass function. It is important for me to dynamically create the class in it.
Try this,
class SuperTest(object):
def func(self):
from Test import Test2
return Test2()
Related
I'm trying to instantiate a class within a function, then call a method within the class inside the same function, like this:
# Define the class
class myclass:
def __init__(self,string_to_print):
self.string_to_print = string_to_print
def myclass_func(self):
print(self.string_to_print)
# Define the function that utilizes the class
def func(class,func,str)
instance = class(str)
class = class.func()
# Run the function that utilizes the class
func(myclass,myclass_func,str)
But I am getting an error like "'myclass' object is not callable". Why is this? Additionally, I expect my 'class = class.func()' line is wrong; if it is, what is the correct way to call the method from the recently instantiated class?
Edit: fixed mistake in class declaration
You can't use method names as global variables. If you want to call a method dynamically, pass its name as a string and use the getattr() function.
# Define the class
class myclass:
def __init__(self,string_to_print):
self.string_to_print = string_to_print
def myclass_func(self):
print(self.string_to_print)
# Define the function that utilizes the class
def func(class,func,str)
instance = class(str)
return getattr(instance, func)()
# Run the function that utilizes the class
func(myclass,'myclass_func',str)
Define your class using the class keyword rather than def.
Create an instance of the class.
Define a function that will try to execute the function given by its name.
class myclass:
def __init__(self,string_to_print):
self.string_to_print = string_to_print
def myclass_func(self):
print(self.string_to_print)
myclass_instance = myclass('Hello world')
def execute_function(instance, function):
getattr(instance, function)()
execute_function(myclass_instance, 'myclass_func')
Output:
Hello world
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'd like to have a class that contains a function that is called whenever another class function is called. And the tricky part is that I'd like this to work for derived classes.
Let's say:
def class A:
def __init__(self):
pass
def b(self):
print("Hello")
and
def class B(A):
def __special_method__(self):
print("Before Hello")
And calling object.b() would print
Before Hello
Hello
Is this even possible?
I have a module of decorators in my_decorators.py which are creating classes and I am importing these decorators into Example.py to use on methods of the Example class:
my_decorators.py
def my_decorator():
def inner_decorator(func):
class CreatedClass(object):
something = 'something'
return CreatedClass
return inner_decorator
Example.py
class Example(object):
# I WANT TO ACCESS THIS SCOPE IN THE DECORATOR
#my_decorator
to_belong_to_newly_created_class(self):
pass
Is there a way to access the local or global scope of Example class or of the Example.py module inside the decorator in the separate module?
def my_decorator(f):
def inner_decorator(self, *args, **kwargs):
print(self.TEST) # Access the required member from self.
class CreatedClass(object):
something = 'something'
return CreatedClass
return inner_decorator
class Example(object):
TEST = 'TEST!!'
# I WANT TO ACCESS THIS SCOPE IN THE DECORATOR
#my_decorator
def to_belong_to_newly_created_class(self):
pass
if __name__ == '__main__':
ex = Example()
print(ex.to_belong_to_newly_created_class())
OUTPUT:
TEST!!
<class '__main__.my_decorator.<locals>.inner_decorator.<locals>.CreatedClass'>
I am confused even after checking many questions asked in SO. I have 2 different class (2 different script) & I want to inherit super class's __init__ method's parameters.
script1.py
class MainClass():
def __init__(self,params):
self.one=params['ONE']
self.two=params['TWO']
self.three=params['THREE']
self.four=params['FOUR']
self.five=params['FIVE']
def a():
#---------
#somecode
#Initializing other class's object to access it's method.
s=SubClass() #HERE I WANT TO PASS 'PARAMS' (WHICH IS A DICTIONARY)
s.method1(....)
script2.py
class SubClass(SuperClass):
def __init__(self,params):
#Here I want all the parameters inside the 'param' in super class.
#(one,two,three...., etc).
#By checking some SO questions, I changed class SubClass() -->
#class Subclass(SuperClass) & below line:
MainClass.__init__(self,params) #But technically I don't have anything
#in param in subclass.
def method1():
#some code...
Since sub class's param doesn't have anything, It gives me an error:
self.one=params['ONE']
TypeError: 'int' object has no attribute '__getitem__'
I am not getting:
How can I access all the parameters of super class to sub class in a simplest way? I don't want to pass individual arguments (like self.one, self.two..) to the sub class.
If I am calling third class inside SubClass -> method1 --> Call 3rd class same as passing 'params'. Is it possible?
Is this what you need?
script1.py
class MainClass():
def __init__(self,params):
# Save params for use by a
self.params = params
self.one=params['ONE']
self.two=params['TWO']
...
self.five=params['FIVE']
def a():
s=SubClass(self.params)
s.method1(...)
script2.py
class SubClass(SuperClass):
def __init__(self,params):
MainClass.__init__(self,params)
def method1():
#some code...
You can pass any and all the non-keyword arguments from the subclass's __init__()to the superclass's like this:
class SubClass(SuperClass):
def __init__(self, *params):
MainClass.__init__(self, *params)
...
This same idea will work for other methods, too.