I have a class A and I have inherited a class B from class A.
I have two methods methodX & methodY in ClassA. This methodY will be calling methodX in classA.
Now I have a methodZ in ClassB.
The following is the scenario:-
class A(object):
def methodX(self):
....
def methodY(self):
methodX()
class B(A)
def methodZ(self):
self.methodY() #says the global methodX is not defined
My question is that I have to call methodY which inturn calls methodX from methodZ. How is it possible? Should I define the methodX globally ? Or is there any other alternative..
Thanks in advance !
In methodY you should be calling self.methodX().
As it has been said before, using self.methodX() seems to be solving your problem.
Check this:
class A(object):
def methodX(self):
print "A.methodX"
def methodY(self):
print "A.methodY"
self.methodX()
class B(A):
def methodZ(self):
print "B.methodZ"
self.methodY()
b = B()
b.methodZ()
Generates this output:
$ python test.py
B.methodZ
A.methodY
A.methodX
$
Which I think it's what you were looking for...
Since a member function cannot be called without using the object of that class, this error is thrown. Using
self.methodX()
Calls the function methodX() using the object using the object used to call the methodY()
Related
I have 2 scripts, 1st is All_Methods, and another is All_Testcases, as I am using unittest framework, so here we go.
All_Methods is like:
class All_Services():
def abc(self):
x =1
def bca(self):
print "My Name is Taimoor"
self.abc()
def cba(self):
self.bca()
and on another script which is All_TestCases is like this:
from All_Methods import All_Services as service
class All_TestCases(unittest.TestCase):
def test_1_running_method(self)
service.cba(self)
Exception showing is:
AttributeError: 'All_TestCases' object has no attribute 'bca'
Kindly someone tell me, what I am missing here?
Thanks.
You are not using classes in the usual way when you pass in self to methods that you call on the class. Common is to call the methods on instances of the class and getting the self argument implicitly.
When you call Method.running_query_Athena(self) self is an instance of All_TestCases which does not have the method connecting_Athena.
Did you mean for All_TestCases to derive from All_Methods?
Why is All_Methods a class at all?
Use proper indentation since python is solely based on the basis of how the code is indented.
Please, Please use proper naming conventions; as advised under PEP 8.
You're trying to access an instance method without an instance.
Try the following:
class MyClass:
def my_instance_method(self):
return True
#classmethod
def my_class_method(cls):
return True
#staticmethod
def my_static_method():
return True
This won't work:
>> MyClass.my_instance_method()
TypeError: my_instance_method() missing 1 required positional argument: 'self'
but these will since they are not bound to a class instance being created.
MyClass.my_class_method()
MyClass.my_static_method()
An instance method requires that you instantiate the Class; meaning you use:
MyClass().my_instance_method()
Since you seem to want to set response_id on the class instance; using the self argument which denotes the class instance to get the response_id. - I suggest that you use an instance method and instantiate the class as shown above (note the () after the class name)
Kindly do fix your formatting in the question.
There are quite a few things wrong with the code in the example, but putting that aside.
The error is caused by passing an instance of class A as the self argument to a (non-static) method of class B.
Python will attempt to call this method on the instance of class A, resulting in the missing attribute error.
Here is a simplified example of the problem:
class A:
def is_ham(self):
# Python secretly does `self.is_ham()` here,
# because `self` is the current instance of Class A.
# Unless you explicitly pass `self` when calling the method.
return True
class B:
def is_it_ham(self):
# Note, `self` is an instance of class B here.
return A.is_ham(self)
spam = B()
spam.is_it_ham()
Can someone explain why I'm getting the error:
global name 'helloWorld' is not defined
when executing the following:
class A:
def helloWorld():
print 'hello world'
class B(A):
def displayHelloWorld(self):
helloWorld()
class Main:
def main:
b = B()
b.displayHelloWorld()
I'm used to java where class B would obviously have a copy of class A's method "helloWorld" and thus this code would run fine when executing main. This however appears to think class B doesn't have any method called "helloWorld"
Missing the self before the helloWorld(). The self keyword means that this an instance function or variable. When class B inherits class A, all the functions in class A can now be accessed with the self.classAfunction() as if they were implemented in class B.
class A():
def helloWorld(self): # <= missing a self here too
print 'hello world'
class B(A):
def displayHelloWorld(self):
self.helloWorld()
class Main():
def main(self):
b = B()
b.displayHelloWorld()
You need to indicate that the method is from that class (self.):
class B(A):
def displayHelloWorld(self):
self.helloWorld()
Python differs in this from Java. You have to specify this explicitly in Python whereas Java accepts implicitly as well.
I don't know what is the version of python used in this example but it seems that syntax looks like python3. (except print statement which looks like python2.x)
Lets suppose that this is python3
I would say that helloWorld is class method of class A and It should be called as class attribute. As soon as this function is in class namespace It can be accessed outside this class only using owner class.
A.helloWorld()
or
B.helloWorld()
or
self.__class__.helloWorld()
You can't call it as bound method in this case because self argument will be passed and as soon as your function doesn't expect it it will fail.
there is possibility that helloWorld is method of A and self parameter is just missed
in this case this method can be called as follow:
self.helloWorld()
or
A.helloWorld(self)
How to access the calling/outer/container python class within current class when added as a property. Consider this example...
class a():
#staticmethod
def meth():
print 'Who called me?'
class b():
my_a = a
class c():
my_a = a
b.my_a.meth()
>> Who called me?
c.my_a.meth()
>> Who called me?
So the question in this example is how to know within a.meth() whether it is being called from class b or class a?
The above are obviously static classes and methods, would the solution to the above also apply to containing objects?
There's no good way to know how the meth() function was accessed. By the time it is called, it is simply a function. If you use #classmethod instead, you will at least get the class passed to you, but in this case, they are both the same a, so I'm not sure you'll get what you want.
You will likely need to do some more bookkeeping to get the information you want.
Using this example from http://docs.python.org/tutorial/classes.html#class-objects:
class MyClass:
"""A simple example class"""
i = 12345
def f(self):
return 'hello world'
According to those docs, f is an attribute reference that returns a function object.
Is there any shorter way of saying what f is? Can I call it a method of a class (note how I didn't say "class method" which is incorrect)? Or a function defined within a class? Or an instance method?
In other words, what's the formal short-hand term for f in terms of its relation to MyClass?
If you're referring specifically to the f returned by MyClass.f, then f is an unbound method of MyClass. Or at least that's what the REPL calls it:
>>> MyClass.f
<unbound method MyClass.f>
In general though, I don't think anyone would fault you for simply calling it a "method", plain and simple. Or, in terms of its relation to MyClass, a method of MyClass.
I'd say it's an instance method(or member function), because this method is only accessible when you bind it with an instance, instance.f() or MyClass.f(instance).
x = MyClass()
def __init__(self):
self.data = []
print x.i
print x.f()
print MyClass.__doc__
# Instance x = MyClass()
# More __init__(self) is important
# Sorry my english. I'm from Brazl
In ruby you can do this:
class A
def self.a
'A.a'
end
end
puts A.a #-> A.a
How can this be done in python. I need a method of a class to be called without it being called on an instance of the class. When I try to do this I get this error:
unbound method METHOD must be called with CLASS instance as first argument (got nothing instead)
This is what I tried:
class A
def a():
return 'A.a'
print A.a()
What you're looking for is the staticmethod decorator, which can be used to make methods that don't require a first implicit argument. It can be used like this:
class A(object):
#staticmethod
def a():
return 'A.a'
On the other hand, if you wish to access the class (not the instance) from the method, you can use the classmethod decorator, which is used mostly the same way:
class A(object):
#classmethod
def a(cls):
return '%s.a' % cls.__name__
Which can still be called without instanciating the object (A.a()).
There are two ways to do this:
#staticmethod
def foo(): # No implicit parameter
print 'foo'
#classmethod
def foo(cls): # Class as implicit paramter
print cls
The difference is that a static method has no implicit parameters at all. A class method receives the class that it is called on in exactly the same way that a normal method receives the instance.
Which one you use depends on if you want the method to have access to the class or not.
Either one can be called without an instance.
You can also access the class object in a static method using __class__:
class A() :
#staticmethod
def a() :
return '{}.a'.format( __class__.__name__ )
At least this works in Python 3.1