To call the class method, you can create an instance of the class and then call an attribute of that instance (the test_def method).
def test(t):
return t
class ClassTest(object):
def test_def(self):
msg = test('Hi')
print(msg)
# Creates new instance.
my_new_instance = ClassTest()
# Calls its attribute.
my_new_instance.test_def()
Alternatively you can call it this way:
ClassTest().test_def()
Sidenote: I made a few changes to your code. self should be used as first argument of class methods when you define them. object should be used in a similar manner.
I have a class that has a ton of methods defined. Due to the size of the file it's becoming cumbersome to edit and maintain. Rather than define all of them in one large .py file in the main module, I'd like to define them in other modules, import them, and then use them as class methods. I've tested the following:
#define the external func
def add_furniture_func(self, new_furniture):
self.furniture.append(new_furniture)
#define the class + use class method to call the external func
class Room():
def __init__(self, furniture):
self.furniture = furniture
def add_furniture(self, new_furniture):
add_furniture_func(self, new_furniture)
room = Room(['couch'])
print(room.furniture)
room.add_furniture('chair')
print(room.furniture)
>> ['couch']
>> ['couch', 'chair']So this works, but I'm wondering if theres a better way to go about it?
Thanks!
python - Call a function outside any method but inside a class? - Stack Overflow
python - How do I use a method outside a class? - Stack Overflow
python - Define a method outside of class definition? - Stack Overflow
@staticmethod called outside class scope (?)
If your method calls a static method on the class, then it does require information on the class. You have a class method, not a static method. By declaring it @classmethod (and adding the cls parameter), you not only properly inform the reader, you allow polymorphism. An inheritor can reimplement the called static method and change behavior.
Python's static methods are intended for methods that are part of a class, and can be called as either a class method or an instance method: both Class.the_method() and self.the_method() would work. When the static method is called, it is not given an implicit first argument:
class Example:
def instance_method_example(self, arguments):
...
@classmethod
def class_method_example(cls, arguments):
...
@staticmethod
def static_method_example(arguments):
...
If you merely want to create a helper function that is used within your class, do not use @staticmethod. Define a free function outside of the class. For example:
class Example:
def some_method(self, argument):
return _helper(argument, self.x)
def _helper(a, b):
...
The background of static methods in Python is the following: when you access an attribute of an object x.attribute or getattr(x, 'attribute'), then this name is looked up in the instance dict or the class dict. If an object is found in the class dict, it is checked whether that object is a “descriptor”: an object that describes how this attribute behaves, not an object that would be directly returned. Descriptors have dunder-methods like __get__, __set__, and __del__ that are invoked depending on whether the descriptor is accessed, assigned to, or deleted with the del operator.
Functions – the things you declare with def – are descriptors. By default, the __get__ descriptor binds the function to the instance argument (typically called self) and returns the bound function, so that it can be invoked as a method. But the various decorators change this behaviour:
- a
@classmethod defbinds to the class object, not the instance - a
@staticmethod defdoes not bind to any object and just returns the underlying function directly - a
@propertyinvokes the underlying function to retrieve a value
These differences are (partially) visible when looking at the repr() of the bound methods. With the first Example class:
instance_method_example- with class:
Example.instance_method_example
is<function Example.instance_method_example at 0x7f1dfdd6fd30>,
the unbound function - with instance:
<function Example.instance_method_example at 0x7f1dfdd6fd30>
is<bound method Example.instance_method_example of <__main__.Example object at 0x7f1dfdddcb80>>,
a method bound to the instance
- with class:
class_method_example- with class:
Example.class_method_example
is<bound method Example.class_method_example of <class '__main__.Example'>>,
a method bound to the class - with instance:
Example().class_method_example
is<bound method Example.class_method_example of <class '__main__.Example'>>,
also a method bound to the class
- with class:
static_method_example- with class:
Example.static_method_example
is<function Example.static_method_example at 0x7f1dfdd6fe50>,
the unbound function - with instance:
Example().static_method_example
is<function Example.static_method_example at 0x7f1dfdd6fe50>,
also the unbound function
- with class:
As a table:
| invoked on… | no decorator | @classmethod |
@staticmethod |
|---|---|---|---|
| … instance | bound to instance | bound to class | unbound |
| … class | unbound | bound to class | unbound |
Yes. You can define a function outside of a class and then use it in the class body as a method:
def func(self):
print("func")
class MyClass:
myMethod = func
You can also add a function to a class after it has been defined:
class MyClass:
pass
def func(self):
print("func")
MyClass.myMethod = func
You can define the function and the class in different modules if you want, but I'd advise against defining the class in one module then importing it in another and adding methods to it dynamically (as in my second example), because then you'd have surprisingly different behaviour from the class depending on whether or not another module has been imported.
I would point out that while this is possible in Python, it's a bit unusual. You mention in a comment that "users are allowed to add more" methods. That sounds odd. If you're writing a library you probably don't want users of the library to add methods dynamically to classes in the library. It's more normal for users of a library to create their own subclass that inherits from your class than to change yours directly.
I'd also add a reminder that functions don't have to be in classes at all. Python isn't like Java or C# and you can just have functions that aren't part of any class. If you want to group together functions you can just put them together in the same module, and you can nest modules inside packages. Only use classes when you need to create a new data type, not just to group functions together.
You can define a function outside of a class and then add it. However, there is a subtle difference in assigning the function to the class or to the instance object. Here is an example:
class MyClass1(object):
def __init__(self, bar):
self.foo = 'up'
MyClass1.foobar = bar
class MyClass2(object):
def __init__(self, bar):
self.foo = 'up'
self.foobar = bar
def bar(self):
return "What's " + self.foo
Let's first look at what is happening in MyClass1. foobar in this class is similar to a normal method as though it was defined inside the class definition (i.e. it is a method bound to the instance of this class). Let's take a look at what this looks like...
In [2]: x = MyClass1(bar)
In [3]: x.foobar
Out[3]: <bound method MyClass1.bar of <__main__.MyClass1 object at 0x104346990>>
In [4]: x.foobar()
Out[4]: "What's up"
How does this differ from MyClass2? In MyClass2, foobar is simply a reference to the bar function and is NOT a bound method. Because of this we must pass the instance in for this function to work properly. e.g.
In [5]: y = MyClass2(bar)
In [6]: y.foobar
Out[6]: <function __main__.bar>
In [7]: y.foobar()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-7-6feb04878e5f> in <module>()
----> 1 y.foobar()
TypeError: bar() takes exactly 1 argument (0 given)
In [8]: y.foobar(y)
Out[8]: "What's up"
Although I'm not sure if this is ever good practice to be doing it this way...
You're calling self.quickSort(), but there is no quickSort in the class. You assigned the function to qsort, so you need to call self.qsort().
Add self as argument of func2. When calling myClass add ().
def func(self):
self.func2()
class myClass:
f = func
def func2(self):
print 'func2'
C = myClass()
C.f()
I want to run all the methods of class A in a method outside that class without having to call each method individually. Is there a way to do this ? everything i see online explains using decorators for different methods but these arent enclosed in a class. I've given an example below for some context
class A
def method_one(something):
bla bla
def method_two(method_one):
yadi yadi ya
def method_three(method_two)
meh
class B
def method_B1
whatevs
if__name__ == 'main'
method from class B
class A(this is where I would want class A doing its thing, calling all of its methods)Hi all I am a bit stuck with some code, any help would be appreciated.
Example:
Class Dog(name, age, breed):
Def __init__(self):
self.name = dog_name
self.age = dog_age
self.breed = dog_breed
Def __str__(self):
return dog_nameI then have a collection of dogs running into another class which has other methods related to graphs.
I am then creating a function outside of the classes to count the number of breeds and output dog name in ascending value.
Everything works fine but I cannot access the dog name, it returns as object memory.
So how do I access the method str in the dog class to get the object name? Is this done using super() ?