Python class static method that requires another static method - python

Is it ok to have multiple staticmethods that calls from each other.
something like:
class Myclass():
def __init__(self, a):
self.var = self.static1(a)
#staticmethod
def static1(i):
i += 1
return self.static2(i)
#staticmethod
def static2(i):
return i * 3
c = Myclass(1)
I got :
NameError: name 'self' is not defined

use the #classmethod decorator
function will denote it does not change anything in the instance while you can access the class via first parameter cls
class Myclass():
def __init__(self, a):
self.var = self.static1(a)
#classmethod
def static1(cls,i):
i += 1
return cls.static2(i)
#staticmethod
def static2(i):
return i * 3

No need to prepend with 'self.'. Just call MyClass.static2(i)

Related

Can we pass the class object inside its own method?

I have a class A object method which uses another class B object's method, which the argument is class A object.
class A():
def calculate(self):
B = B.calculator(A)
class B():
def calculator(self, A):
...do something with A.attributes
It is possible to just pass attributes into the object, but I would see this possibility as the last priority. I am definitely a bit oversimplify my case, but I am wondering if there is a way to pass the entire class
Edit:
Sorry for the confusion. At the end I am trying to call class A object and A.calculate(), which will call class B obj and calculator function.
class A():
def __init__(self, value):
self.value = value
def calculate(self):
Bobj = B()
Bobj.calculator(A)
class B():
def calculator(self, A):
...do something with A.value
def main():
Aobj = A(value)
Aobj.calculate()
Your scenario does not currently indicate that you want to use any information from B when calculating A. There are a few ways of getting the functionality that you want.
Scenario: B stores no information and performs calculation. B should be a function
def B(value):
```do something with value```
return
class A():
def __init__(self, value):
self.value = value
def calculate(self):
return B(self.value)
def main():
Aobj = A(value)
Aobj.calculate()
Scenario: B stores some other information, but internal B information is not needed for the calculation. B should have a static method
class B():
#staticmethod
def calculate(value):
```do something with value```
return
class A():
def __init__(self, value):
self.value = value
def calculate(self):
return B.calculate(self.value)
def main():
Aobj = A(value)
Aobj.calculate()

How to pass function to class with specific arguments?

I like to pass a function which has 2 arguments to a class where 1 of the arguments are "predefined". When I call the function from within a class instance, I only want to give the second variable (because I already defined the first). Example:
def my_fun(a, b):
return a+b
class MyClass():
def __init__(self, fun):
self._fun = fun
def class_function(self, c):
return self._fun(c)
instance = MyClass(my_fun(a=5.0))
print(instance.class_function(10.0))
Is this possible?
Use partial from functools module.
from functools import partial
def my_fun(a, b):
return a + b
class MyClass():
def __init__(self, fun):
self._fun = fun
def class_function(self, c):
return self._fun(c)
instance = MyClass(partial(my_fun, 5.0))
print(instance.class_function(10.0))

How to call class method within namespace of the same class in python 3.x

When working with python instances, it is possible to access bound methods of the same class using self. This resolves to a method corresponding to the same class in hierarchy.
class A:
def f(self):
return 1
def __init__(self):
self.v = self.f()
class B(A):
def f(self):
return 2
b = B()
# b.v is set to 2
But, when working with class methods, there is no apparent way of accessing methods of the same class as above.
In my use case, f above needs to be a class method and I need to set class variable v according to f corresponding to the same class. Somewhat like:
class A:
#classmethod
def f(cls):
return 1
v = resolution_of_calling_class.f()
class B(A):
#classmethod
def f(cls):
return 2
# B.v should be 2
edit: v is actually an attribute defined by parent class, which should find a method overridden by child class
You just need to override __new__ method, since it is invoked before the __init__ and its purpose is to create an instance, that will be initialized by __init__.
class A:
def __new__(cls, *args, **kwargs):
cls.v = cls.f()
return super().__new__(cls, *args, **kwargs)
#classmethod
def f(cls):
return 1
class B(A):
#classmethod
def f(cls):
return 2
a = A()
print(a.v)
b = B()
print(b.v)
1
2
I am not 100% sure I understand what you are trying to do.
I used your code above and
class A:
#classmethod
def f(cls):
return 1
class B:
#classmethod
def f(cls):
return 2
print(B.f())
gives me 2 just as I expected it would. Should B be a child class of A as in the first example?

Using a method both inside a class and outside - python

So I have a function that, so far, I have had as a method inside a class. Turns out now I want to use it without making an instance of the class.
What is the best way of doing this without having to massively change the code?
Example codes follow:
Before:
class A(object):
def method1(self, input):
return input*3 + 7
def method2(self, input):
return self.method1(input) + 4
Basically I want to take method1 out of the class so that i can use it without making an instance of A, but also do not want change self.method1 to method1 everywhere.
My idea:
def method1(input):
return input*3 + 7
class A(object):
def __init__(self):
self.method1 = method1
def method2(self, input):
return self.method1(input) + 4
--
Is this bad practice? How else could one call a method from inside a class? Or alternatively how can a class incorporate methods methods outside it?
Try this:
def method1(input):
return input*3 + 7
class A(object):
def method1(self, input):
return method1(input)
def method2(self, input):
return self.method1(input) + 4
this should work
It won't work because of the self parameter. Instead, define it like this:
class A(object):
def method1(self, input):
return method1(input)
This is called a static method in order to do this, your function can not contain (self)
class A(object):
def method_one(variable):
return variable * 3 + 7
def method_two(self, variable):
return self.method_one(variable) + 4
print(A.method_one(10))
(xenial)vash#localhost:~/python/stack_overflow$ python3.7 method_out.py
37
Turn into a staticmethod the method you don't need or don't want an instance of its class.
The ideia would be like the following:
>>> class A:
#staticmethod
def m(value):
return value*3+7
def sum(self, value):
return self.m(value) + 4
>>> a = A()
>>> a.sum(4)
23
>>> 4+A.m(4)
23
>>>
Notice the difference from a normal method to the static one. On the static one you ommit the self parameter, thus meaning you don't need an instance of its class to use that static method.

Python Decorators and inheritance

Help a guy out. Can't seem to get a decorator to work with inheritance. Broke it down to the simplest little example in my scratch workspace. Still can't seem to get it working.
class bar(object):
def __init__(self):
self.val = 4
def setVal(self,x):
self.val = x
def decor(self, func):
def increment(self, x):
return func( self, x ) + self.val
return increment
class foo(bar):
def __init__(self):
bar.__init__(self)
#decor
def add(self, x):
return x
Oops, name "decor" is not defined.
Okay, how about #bar.decor? TypeError: unbound method "decor" must be called with a bar instance as first argument (got function instance instead)
Ok, how about #self.decor? Name "self" is not defined.
Ok, how about #foo.decor?! Name "foo" is not defined.
AaaaAAaAaaaarrrrgggg... What am I doing wrong?
Define decor as a static method and use the form #bar.decor:
class bar(object):
def __init__(self):
self.val = 4
def setVal(self,x):
self.val = x
#staticmethod
def decor(func):
def increment(self, x):
return func(self, x) + self.val
return increment
class foo(bar):
def __init__(self):
bar.__init__(self)
#bar.decor
def add(self, x):
return x
I know the question has been asked 11 years ago ...
I had the same problem, here is my solution to use an inherited private decorator :
class foo:
def __bar(func):
def wrapper(self):
print('beginning')
func(self)
print('end')
return wrapper
class baz(foo):
def __init__(self):
self.quux = 'middle'
#foo._foo__bar
def qux(self):
print(self.quux)
a = baz()
a.qux()
The output is :
beginning
middle
end

Categories