Python subclasses calling parent function - python

class A():
class B():
def Foo(self):
print "Hello"
class C():
def Bar(self):
print "Goodbye"
def name(self):
print "FooBar"
What I want to do is, within the Bar function is call the Foo function. How would I do that?

In Python, inner classes don't have an implicit instance of the outer class associated with them. Without such an instance, you can't call A's non-static methods from B or C.
If you do have such an instance, then simply use the dot notation:
class C():
def Bar(self):
self.a.name()
...
(where self.a is an instance of A.)
Alternatively, if A.name() can be made static, the following will also work:
class A(object):
class C():
def Bar(self):
print "Goodbye"
A.name()
#staticmethod
def name():
print "FooBar"
A.C().Bar()

You need an instance of class A to call a method.

Related

Pass method to function using method name from string variable

I have a class with a constructor, two other methods, and a member list with the names of the two methods.
class Foo():
def __init__(self):
self.methods = ["self.foo", "self.bar"]
def foo(self):
print("foo")
return 0
def bar(self):
print("bar")
return 0
I have a function that takes a function as an argument, like this.
myFunction(func)
The function has global scope and would be used like this.
myFunction(self.foo)
I want to iterate through the items in the self.methods list and make a call to the function for each method name, but, as expected, a string is passed rather than the method itself. How do I pass the method like the above example, so like self.foo not "self.foo"?
From what I understand you can try this.
class Foo():
def __init__(self):
self.method=['foo','bar']
def foo(self):
print('foo')
def bar(self):
print('bar')
def run_all(self):
for m in self.method:
getattr(self,m)()
a=Foo()
a.run_all() # iterating through self.method and executing them
# foo
# bar
You want somwthing like this?
class Foo():
def __init__(self):
self.methods = [self.foo(), self.bar()]
def foo(self):
print("foo")
return 0
def bar(self):
print("bar")
return 0
foo_obj = Foo()
What about:
class Foo():
def __init__(self):
self.methods = self.foo, self.bar
def run_methods(self):
for method in self.methods:
print('Running method {}'.format(method.__name__))
method()
def foo(self):
print("foo")
return 0
def bar(self):
print("bar")
return 0
So, you can run your methods by calling run_methods. If you want to access their names as well, you can always do that via their respective __name__ methods, as above.
f = Foo()
f.run_methods()
# Output:
#
# Running method foo
# foo
# Running method bar
# bar
EDIT: As another person suggested, you should edit your question to describe in more detail what myFunction(fun) does. But inded, you should probably use a different approach than passing the actual names as strings.

How to call sub function in a class in python?

(I'm very new to both python and stackoverflow.)
def A():
def B():
print("I'm B")
A.B = B
A()
A.B()
output:
"I'm B"
This works well. What I want is to put that in a class like this(doesn't work. I just tried..)
class Student:
def A(self):
def B():
print("I'm B")
self.A.B = B
I have no Idea how to make the class and how to call the sub function in the class.
Python functions are first-class objects. What is first class function in Python
So the first piece of code is perfectly valid. It just adds a property B to the function, which can later be called using A.B().
But for the second piece of code, this is invalid, as self.A returns a reference to A method of class Student
<bound method Student.A of <__main__.Student object at 0x7f5335d80828>>
self.A does not have an attribute B, so it returns an error
AttributeError: 'method' object has no attribute 'B'
Now a quick fix would be to assign it to self.B
class Student:
def A(self):
def B():
print("I'm B")
self.B = B
a = Student()
a.A()
a.B()
Although the above code works, it is a very bad way, as you will have to always call A for every object instantiated before calling B.
You don't need to reference self because the inner function B is defined there. It should be like this:
class Student:
def A(self):
def B():
print("I'm B")
B()
I never use classes, but could you do it this way?
class A:
def __call__(self): // so you can call it like a function
def B():
print("i am B")
B()
call_A = A() // make the class callable
call_A() // call it

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

How do I call a method on a specific base class in Python?

How do I call a method on a specific base class? I know that I can use super(C, self) in the below example to get automatic method resolution - but I want to be able to specify which base class's method I am calling?
class A(object):
def test(self):
print 'A'
class B(object):
def test(self):
print 'B'
class C(A,B):
def test(self):
print 'C'
Just name the "base class".
If you wanted to call say B.test from your C class:
class C(A,B):
def test(self):
B.test(self)
Example:
class A(object):
def test(self):
print 'A'
class B(object):
def test(self):
print 'B'
class C(A, B):
def test(self):
B.test(self)
c = C()
c.test()
Output:
$ python -i foo.py
B
>>>
See: Python Classes (Tutorial)

How can I tell what class in the polymorphic hierarchy contains the method I'm about to call?

If I have:
class A():
def f(self):
print("running function, f from class A")
class B(A):
def __init__(self):
A.__init__(self)
def f(self):
print("running function, f from class B")
and I make an instance of class B and call f on it, we all know we'll see the message about "from class B." But is there a way for me to inspect my object and make sure my sub-class has overridden my method? Something like:
obj = B()
assert(not obj.f.livesIn(A))
class A():
def f(self):
print("running function, f from class A")
class B(A):
def f(self):
print("running function, f from class B")
class C(A):
pass
This shows that B.f does not equal A.f. So B must override f:
obj = B()
print(obj.__class__.f == A.f)
# False
This shows that C.f equals A.f. So C must not have overridden f:
obj = C()
print(obj.__class__.f == A.f)
# True
If you want to force the child class to override, you can raise NotImplementedError().
Doing the inspection is possible too... And I see unutbu just posted an example, so I won't repeat it. :)

Categories

Resources