Calling a Class Method Within a Class

How can I access a classmethod from inside a class in Python

At the time that x=10 is executed in your example, not only does the class not exist, but the classmethod doesn't exist either.

Execution in Python goes top to bottom. If x=10 is above the classmethod, there is no way you can access the classmethod at that point, because it hasn't been defined yet.

Even if you could run the classmethod, it wouldn't matter, because the class doesn't exist yet, so the classmethod couldn't refer to it. The class is not created until after the entire class block runs, so while you're inside the class block, there's no class.

If you want to factor out some class initialization so you can re-run it later in the way you describe, use a class decorator. The class decorator runs after the class is created, so it can call the classmethod just fine.

>>> def deco(cls):
... cls.initStuff()
... return cls
>>> @deco
... class Foo(object):
... x = 10
...
... @classmethod
... def initStuff(cls):
... cls.x = 88
>>> Foo.x
88
>>> Foo.x = 10
>>> Foo.x
10
>>> Foo.initStuff() # reinitialize
>>> Foo.x
88

Calling method, classmethod, staticmethod in the same Python class

Yes, your guesses will work. Note that it is also possible/normal to call staticmethods and classmethods outside the class:

class A():
...

A.class_foo()
A.static_foo()

Also note that inside regular instance methods, it's customary to call the staticmethods and class methods directly on the instance (self) rather than the class (A):

class A():
def instance_method(self):
self.class_foo()
self.static_foo()

This allow for inheritance to work as you might expect -- If I create a B subclass from A, if I call B.instance_method(), my class_foo function will get B instead of A as the cls argument -- And possibly, if I override static_foo on B to do something slightly different than A.static_foo, this will allow the overridden version to be called as well.

Some examples might make this more clear:

class A(object):
@staticmethod
def static():
print("Static, in A")

@staticmethod
def staticoverride():
print("Static, in A, overrideable")

@classmethod
def clsmethod(cls):
print("class, in A", cls)

@classmethod
def clsmethodoverrideable(cls):
print("class, in A, overridable", cls)

def instance_method(self):
self.static()
self.staticoverride()
self.clsmethod()
self.clsmethodoverride()

class B(A):
@classmethod
def clsmethodoverrideable(cls):
print("class, in B, overridable", cls)

@staticmethod
def staticoverride():
print("Static, in B, overrideable")

a = A()
b = B()
a.instance_method()
b.instance_method()

...

After you've run that, try it by changing all of the self. to A. inside instance_method. Rerun and compare. You'll see that all of the references to B have gone (even when you're calling b.instance_method()). This is why you want to use self rather than the class.

invoking a class method inside the class itself

Something like this seems to be what you're looking for:

class Something:
def __init__(self):
self.__sum(1, 2)

def __sum(self, variable_1, variable_2):
self.summation = sum(variable_1, variable_2)

Not saying this is the ideal approach or anything, but you haven't really given us much to go off of.

In general, make sure self is the first argument in all class methods, and you can call that class method at any time using either self.method_name() if you are using it from within another class method or instance.method_name() if you're using it externally (where instance = Something()).

How can I call a function within a class?

Since these are member functions, call it as a member function on the instance, self.

def isNear(self, p):
self.distToPoint(p)
...

How to access class method within class but outside class methods or member functions?

You have 2 possibilities :

  • use getB.__func__()
  • use A.getB() in another function within the class

Try this :

class A():
@staticmethod
def getB():
return ['B', 'BB']

list_B = getB.__func__()
print("list_B_1", list_B)

def foobar(self):
list_B_2 = A.getB()
print("list_B_2", list_B_2)

a = A()
a.foobar()

Calling class method within class error

The error comes from this line:

return (self.reverse(self.text) == self.text)

change it for this:

return (self.reverse() == self.text)

self can be really confusing, here is a really good article to understand how it works. Just so you understand, look at reverse() definition:

def reverse(self):
return self.text[::-1]

As you can see, self.text is already assigned. No need to pass it to the function when calling it.

Call Class Method From Another Class

update: Just saw the reference to call_user_func_array in your post. that's different. use getattr to get the function object and then call it with your arguments

class A(object):
def method1(self, a, b, c):
# foo

method = A.method1

method is now an actual function object. that you can call directly (functions are first class objects in python just like in PHP > 5.3) . But the considerations from below still apply. That is, the above example will blow up unless you decorate A.method1 with one of the two decorators discussed below, pass it an instance of A as the first argument or access the method on an instance of A.

a = A()
method = a.method1
method(1, 2)

You have three options for doing this

  1. Use an instance of A to call method1 (using two possible forms)
  2. apply the classmethod decorator to method1: you will no longer be able to reference self in method1 but you will get passed a cls instance in it's place which is A in this case.
  3. apply the staticmethod decorator to method1: you will no longer be able to reference self, or cls in staticmethod1 but you can hardcode references to A into it, though obviously, these references will be inherited by all subclasses of A unless they specifically override method1 and do not call super.

Some examples:

class Test1(object): # always inherit from object in 2.x. it's called new-style classes. look it up
def method1(self, a, b):
return a + b

@staticmethod
def method2(a, b):
return a + b

@classmethod
def method3(cls, a, b):
return cls.method2(a, b)

t = Test1() # same as doing it in another class

Test1.method1(t, 1, 2) #form one of calling a method on an instance
t.method1(1, 2) # form two (the common one) essentially reduces to form one

Test1.method2(1, 2) #the static method can be called with just arguments
t.method2(1, 2) # on an instance or the class

Test1.method3(1, 2) # ditto for the class method. It will have access to the class
t.method3(1, 2) # that it's called on (the subclass if called on a subclass)
# but will not have access to the instance it's called on
# (if it is called on an instance)

Note that in the same way that the name of the self variable is entirely up to you, so is the name of the cls variable but those are the customary values.

Now that you know how to do it, I would seriously think about if you want to do it. Often times, methods that are meant to be called unbound (without an instance) are better left as module level functions in python.

calling a method inside a class-Python

You haven't created an object to the above class.

Any function/method inside a class can only be accessed by an object of that class .For more information on the fundamentals of Object Oriented Programming, please check this page.

Meanwhile for this to work, define your class in the following way :

class Time:

def __init__(self,x=None,y=None,z=None):
self.hour=x
self.minute=y
self.second=z

def __str__(self):
return "({:02d}:{:02d}:{:02d})".format(self.hour, self.minute, self.second)

def time_to_int(time):
minutes=time.hour*60+time.minute
seconds=minutes*60+time.second
return seconds

def int_to_time(seconds):
time=Time()
minutes,time.second=divmod(seconds,60)
time.hour,time.minute=divmod(minutes,60)
return time

def add_time(t1,t2):
seconds=time_to_int(t1)+time_to_int(t2)
return int_to_time(seconds)

and outside the class block, write the following lines :

TimeObject = Time()
start=Time(9,45,00)
running=Time(1,35,00)
TimeObject.add_time(start,running)
print "done"

I however suggest you to write the add_time function outside the class because you are passing the objects to the class as the parameters to the function within the same class and it is considered as a bad design in object oriented programming.
Hope it helps. Cheers!

Calling one method from another within same class in Python

To call the method, you need to qualify function with self.. In addition to that, if you want to pass a filename, add a filename parameter (or other name you want).

class MyHandler(FileSystemEventHandler):

def on_any_event(self, event):
srcpath = event.src_path
print (srcpath, 'has been ',event.event_type)
print (datetime.datetime.now())
filename = srcpath[12:]
self.dropbox_fn(filename) # <----

def dropbox_fn(self, filename): # <-----
print('In dropbox_fn:', filename)

Calling method within Class

class TestClass
# a class method
def self.test_method
puts "Hello from TestClass"
end

# an instance method
def test_method
puts "Hello from an instance of TestClass"
end
end

# call the class method
TestClass.test_method

# create and instance object of TestClass
instance_of_TestClass = TestClass.new

# call the instance method of the new object
instance_of_TestClass.test_method


Related Topics



Leave a reply



Submit