This question already has an answer here:
Assign external function to class variable in Python
(1 answer)
Closed 3 years ago.
In my class I'd like to call a non-member function whose reference is stored in a member variable. My issue is that it tries to pass self to the function as the first argument. How can I avoid this?
class MyClass:
my_useful_static_function = crcmod.mkCrcFun(0x11021, True)
def __init__(self):
# this gets called with the first argument as self :(
result = self.my_useful_static_function()
Use staticmethod:
class MyClass:
my_useful_static_function = staticmethod(crcmod.mkCrcFun(0x11021, True))
def __init__(self):
result = self.my_useful_static_function()
You need to use staticmethod like so:
class Foo:
#staticmethod
def my_method():
print("This is a static method")
def my_other_method(self):
print("This is not static")
# This works
Foo.my_method()
# This won't work
Foo.my_other_method()
# This works though
foo_instance = Foo()
foo_instance.my_other_method()
Related
This question already has answers here:
How can I access "static" class variables within methods?
(6 answers)
Closed 3 years ago.
class MyClass(object):
code_mapping = {...}
def get_name(code):
code = code_mapping[code]
...
In this piece of code, it complains that 'code_mapping is not defined'. Isn't code_mapping is accessible to everything within MyClass?
Initialize it with self. This will make it accessible by any function in the class by passing it with self.<variable> and then passing self as a function argument to anything you want to pass the variable to.
class MyClass(object):
def __init__(self):
self.code_mapping = {...} # if this will be a hard coded
def get_name(self):
code = self.code_mapping[code]
...
Or you could do:
class MyClass(object):
def __init__(self, code_mapping):
self.code_mapping = code_mapping
def get_name(self):
code = self.code_mapping[code]
...
if you'd like to pass some code mapping as an argument to your class at its instantiation.
To create a class object from this where you want {'code1' : 'name'} you then initiate a class object like this:
code1 = MyClass({'code1' : 'name'})
And then {'code1' : 'name'} will be what is carried forth into whatever get_name() does and the value of code in get_name will be name.
This question already has answers here:
TypeError: Missing 1 required positional argument: 'self'
(8 answers)
Closed 2 years ago.
I know a similar question has been asked/answered several times. But please do read on ..
I am trying to create a Class from a string value as described in "Convert string to Python Class Object" in Python 3.6.
utils.py
class Foo(object):
def __init__(self):
print("In the constructor of Foo")
def What(self):
print("so what ... ")
class FooParam(object):
def __init__(self, v):
self.value = v
print("In the constructor of FooParam")
def What(self):
print("Value=" % self.value)
print("So what now ...")
welcome.py
def TEST1():
m = importlib.import_module("utils")
c = getattr(m, "Foo")
c.What()
if __name__ == '__main__':
TEST1()
Error
TypeError: What() missing 1 required positional argument: 'self'
So what am I doing wrong ?
Also how can I create an object of "FooParam" and pass a value to the constructor.
Once you import the module just access with the variable you stored imported module:
m = importlib.import_module("utils")
foo = m.Foo()
foo.What()
import_module performs the same steps as import.
This c = getattr(m, "Foo") line of code is equivalent f = Foo so that means you are not creating an instance instead you are getting a reference to that class.
I suspect that c is the class Foo but not an instance of the class.
This is equivalent to simply calling
Foo.what()
Which is why self is not defined!
Whereas what you want is to create an instance of the class (giving it a 'self' property), then call its method, i.e.
foo_instance = Foo()
foo_instance.What()
so try replacing c.What() with..
foo_instance = c()
foo_instance.What()
for FooParam:
#import the class FooParam
c = getattr(m, "FooParam")
#create an instance of the class, initializing its values (and self)
fooparam_instance = c(3.14)
#call its method!
fooparam_instance.What()
on the whole I would rename the variable c, to something like foo_import and fooparam_import respectively :)
This question already has answers here:
Python NameError: name is not defined
(4 answers)
Closed 4 years ago.
class one(object):
b=squares
def squares(self):
print('hi')
getting the following error:
NameError: name 'squares' is not defined
This should work for you. Let me explain it. First code should go inside of methods, these methods can be combined into classes. You shouldn't place code in the class directly.
In Python when an object is instantiated the __init__(self) method is called directly. This method takes the self argument which will hold the attributes and functions available for this class. In our case, I added an attribute called self.size = 5. Then we call the squares(self) function. Notice we access it as self.function_name().
Then in that function we pass the self argument. Notice how we can access the self.size attribute from this function.
class one(object):
def __init__(self):
self.size = 5
b = self.squares()
def squares(self):
print('hi' + str(self.size))
o = one()
If you want a generic function not tied to your object. Then you need to define it before the class.
def squares(a):
return a*a
class One():
def __init__(self, a):
self.num = a
self.example()
def example(self):
b=squares(self.num)
print(b)
obj = One(4)
This question already has an answer here:
Destroy object method after first invocation
(1 answer)
Closed 5 years ago.
class something(object):
def __init__(self):
pass
def method1(self):
pass
def method2(self):
pass
def method3(self):
pass
def disable_method12(self):
I want to write a method "disable_method12" that disables method1 and method2 in my class but won't disable method3, how can I do this? shall I write
def disable_method12(self):
method1(self) = False
method2(self) = False
you could delete the method like this:
def disable_method12(self):
del something.method1
del something.method2
or better like this (thanks #volcano) so you can rename your class and it still works
def disable_method12(self):
del self.__class__.method1
del self.__class__.method2
testing this for method2 call:
s = something()
s.method2() # first time it works
s.disable_method12()
s.method2()
I get at the last line:
AttributeError: 'something' object has no attribute 'method2'
This question already has answers here:
Adding a method to an existing object instance in Python
(19 answers)
Closed 7 years ago.
In my model I have a class containing a rather generic function, which calls a higher order function. I put together a simple example of it:
class AClass(object):
def __init__(self, prop, fun):
self.prop = prop
self.fun = fun
def do_sth(self):
self.fun()
def namely_this_(context):
print 2*context.prop
obj1 = AClass(3, namely_this_)
obj1.do_sth()
This snippet contains everything to know, just note, that it could be continued by something like:
def namely_this_2(self):
print 4*self.prop
obj2 = AClass(2, namely_this_2)
obj2.do_sth()
The above code does not run, instead it throws a
TypeError: namely_this_() takes exactly 1 argument (0 given)
Instead, I have to change the do_sth to
def do_sth(self):
self.fun(self) # the *self* in the parenthesis added
Question: In what way does the namely_this_ differ from functions defined inside a class and is my workaround a viable solution?
An instance method is a property of the class, not the instance itself. If you changed your init to assign fun to self.__class__.fun, it would work; except then of course all instances would share the same function, which is clearly not what you want.
In order to make it an actual method, you need to make it an instance of types.MethodType:
def __init__(self, prop, fun):
self.prop = prop
self.fun = types.MethodType(fun, self)