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)
Related
I have the following code:
import numpy as np
class ClassProperty(property):
def __get__(self, cls, owner):
return self.fget.__get__(None, owner)()
def coord(cls, c):
if cls.dimension <= 2:
return c
else:
return c + [0]*(cls.dimension-2)
class Basis_NonI(object):
#ClassProperty
#classmethod
def zerocoord(cls):
return coord(cls, [0,0])
def __init__(self, dimension):
pass
class Basis_D(Basis_NonI):
dimension = 2
proj_matrix = np.array([Basis_D.zerocoord, Basis_D.zerocoord])
def __init__(self, dimension):
super(Basis_D, self).__init__(Basis_D.dimension)
where basically I want dimension and proj_matrixto be class attributes of Basis_D.
When I run it, the following error is given:
proj_matrix = np.array([Basis_D.zerocoord, Basis_D.zerocoord])
NameError: name 'Basis_D' is not defined
--
What I don't understand is that I can use Basis_D.dimension in the init, so why does it not recongise the name Basis_D when I use it to define proj_matrix?
class is an executable statement. When the module is first imported (for a given process), all the code at the top-level of the class statement is executed, all names defined that way are collected into a dict, then the class object is created with this dict, and finally bound to the class name. IOW, at this point:
class Basis_D(Basis_NonI):
dimension = 2
# HERE
proj_matrix = np.array([Basis_D.zerocoord, Basis_D.zerocoord])
the class has not yet been created nor bound to the name Basis_D.
Now by the time __init__ is called, the class has already been created and bound to the module-level name Basis_D, so the name can be resolved.
FWIW, you shouldn't directly reference Basis_D in your methods, but type(self) (or even self - if a name is not resolved as an instance attribute, it's looked up on the class).
Also, why do you insist on using class attributes ? Do you understand that your project_matrix array will be shared amongst all instances of Basis_D ?
Basis_D gets created once all the statements inside it are executed and reaches the end.
You can check that using globals() dictionary.
class Basis_D(Basis_NonI):
dimension = 2
print('Basis_D got created?:',bool(globals().get('Basis_D')))
#proj_matrix = np.array([Basis_D.zerocoord, Basis_D.zerocoord])
def __init__(self, dimension):
super(Basis_D, self).__init__(Basis_D.dimension)
print('Basis_D got created?:',bool(globals().get('Basis_D')))
=================== RESTART: D:/PythonWorkspace/sometry.py ===================
Basis_D got created?: False
Basis_D got created?: True
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 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()
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:
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)