using class attributes function in class method - python - python

I'm trying to use this code in python:
class A:
func = lambda: "go away"
#classmethod
def apply(cls):
cls.func()
A.apply()
And I receive this error:
unbound method <lambda>() must be called with A instance as first argument (got nothing instead)
How can I make it work?

Doing apply(A) works. However you will need to fix the issues with func as well.

So here you have a bunch of problems. I am not really sure what you are trying to achieve, but you definitely have to take another look on documentation.
First, take a look on your class.
Inside you want to specify a function, and Python uses a def func(args) method to it. If you want to use it inside a class, you should use self as a parameter.
From the documentation:
class MyClass:
"""A simple example class"""
i = 12345
def f(self):
return 'hello world'
Also, lambda, in words is an anonymous function. When you define it, you should do something like:
s = lambda x: x**2
s(2)
and x would be your function parameter, and x**2 something you want to return, so the function will return 4.
Hope it will reduce some mess and you will write your code in a better way. Good luck!

Related

Can I wrap a complete class using a decorator in python?

I have a complex function with many parameters. I have the idea to use a class, module, funcion, etc, where I define the parameters, and procedures that I will pass to the big function.
I wrote this code that actually works. But I dont know if it is "legal" to do so.
from functools import wraps
def myfunc (value) :
print 'myfunc' , value
def somewrapper (f):
#wraps(f)
def decorated_class () :
print "inside wrapper"
print hasattr(f,'foomember')
return myfunc ('wrapped')
return decorated_class
#somewrapper
class mymodelclass :
some = 'value'
def foomember () :
return 'inside class'
mymodelclass()
Yes, class decorators are supported and perfectly valid to use in Python. The ability was introduced in Python 2.6, via PEP 3129. So, the following two pieces of code are identical:
class A:
pass
A = foo(bar(A))
#foo
#bar
class A:
pass
The code sample you provided doesn't really make much sense to me, since you've replaced the mymodelclass with a function object that doesn't return anything when you execute it, but it looks like that's just a toy example you're using to demonstrate the idea.

Python 3: Calling a Function from a class, self

I am trying to learn about classes, can someone explain to me why this code is not working. I thought when calling a function from a class, "self" is automatically ommitted, but the interpreter tells me that argument "a" is missing (he thinks self = 10).
#! coding=utf-8
class test:
def __init__(self):
"do something here"
def do(self,a):
return a**2
d = test.do
print(d(10))
Instantiate the class first:
d = test().do
print(d(10)) # prints 100
test.do is an unbound method, test().do is bound. The difference is explained in this thread: Class method differences in Python: bound, unbound and static.
You have to instantiate the class first:
d = test()
then you can call a method:
print(d.do(10))
if you want to use method statically you have to declare it in python
#! coding=utf-8
class test:
def __init__(self):
"do something here"
#staticmethod
def do(a):
return a**2
d = test.do
print(d(10)) #and that's work
Since you haven't instantiated the class (a fancy term for created) you can't be assigning methods to any random variable. Like already said, you must create the object first, whilst making sure the method you call is a part of the class you called or connected to the class in some way (such as creating another class and then communicating that class with the current class). So you should first type d=test() followed by d.do().
Also, remember that in your declaration of the method you crated a parameter so what you done was wrong in itself anyway, because when you declared the do function, you should have put within the brackets the number you wanted to send to the method to calculate its square. So you type test.do(10) and then the 10 is sent by the self reference to the method to be done whatever it is you told it to do.
One more thing: although it isn't a huge deal, it helps if all of your class names begin with a capital letter, as this is usually the 'pythonic' way to do things, and it also makes your code much easier to read, because when you first called the class, somebody could easily mistaken it for an ordinary function
class test:
def __init__(self):
"do something here"
def do(self,a):
return a**2
def __call__(self,a):
return self.do(a)
a = test
test.do(a,10)
#or
a = test().do
a(10)
#or
a = test()
test.do(a,10)
#or
a = test()
print(a(10))

Python member function decorators use instance as a parameter

How to use instance as a parameter in the python member function decorators.
The following is an example.
def foo(func):
def wrap(s):
func()
s.ma()
return wrap
class A:
def ma(self):
print "this is ma"
#foo(self) #error.name 'self' is not defined
def mb(self):
print "this is mb"
It's not clear what you're looking for, but if you want to be able to use the reference to the instance inside your decorator:
def foo(func):
def wrap(s): # I'd call this 'self' instead of 's' to remind us it's a reference to an instance
func(s) # This is a function, not a method yet - so we need to pass in the reference
s.ma() # This is a method, because you use attribute lookup on the object s to get it
return wrap
class A:
def ma(self):
print "this is ma"
#foo # if the way foo wraps mb doesn't depend on some arg, don't use args here
def mb(self):
print "this is mb"
I think you're confused here about the difference between methods and functions in Python – you seem to expect func will work like a method, when in fact it will still be a function when it is being decorated. It is the decorated function that will, at attribute lookup on the instance, be turned into a method; this means you still need the explicit self when you call func in your wrapper function.
See the terrific answer to How to make a chain of function decorators? for a better explanation of what's going on.

Using the self-parameter in python objects

I've got a question about defining functions and the self-parameter in python.
There is following code.
class Dictionaries(object):
__CSVDescription = ["ID", "States", "FilterTime", "Reaction", "DTC", "ActiveDischarge"]
def __makeDict(Lst):
return dict(zip(Lst, range(len(Lst))))
def getDict(self):
return self.__makeDict(self.__CSVDescription)
CSVDescription = __makeDict(__CSVDescription)
x = Dictionaries()
print x.CSVDescription
print x.getDict()
x.CSVDescription works fine. But print x.getDict() returns an error.
TypeError: __makeDict() takes exactly 1 argument (2 given)
I can add the self-parameter to the __makeDict() method, but then print x.CSVDescription wouldn't work.
How do I use the self-parameter correctly?
In python, the self parameter is implicitly passed to instance methods, unless the method is decorated with #staticmethod.
In this case, __makeDict doesn't need a reference to the object itself, so it can be made a static method so you can omit the self:
#staticmethod
def __makeDict(Lst): # ...
def getDict(self):
return self.__makeDict(self.__CSVDescription)
A solution using #staticmethod won't work here because calling the method from the class body itself doesn't invoke the descriptor protocol (this would also be a problem for normal methods if they were descriptors - but that isn't the case until after the class definition has been compiled). There are four major options here - but most of them could be seen as some level of code obfuscation, and would really need a comment to answer the question "why not just use a staticmethod?".
The first is, as #Marcus suggests, to always call the method from the class, not from an instance. That is, every time you would do self.__makeDict, do self.__class__.__makeDict instead. This will look strange, because it is a strange thing to do - in Python, you almost never need to call a method as Class.method, and the only time you do (in code written before super became available), using self.__class__ would be wrong.
In similar vein, but the other way around, you could make it a staticmethod and invoke the descriptor protocol manually in the class body - do: __makeDict.__get__(None, Dictionaries)(__lst).
Or, you could detect yourself what context its being called from by getting fancy with optional arguments:
def __makeDict(self, Lst=None):
if Lst is None:
Lst = self
...
But, by far the best way is to realise you're working in Python and not Java - put it outside the class.
def _makeDict(Lst):
...
class Dictionaries(object):
def getDict(self):
return _makeDict(self.__CSVDescription)
CSVDescription = _makeDict(__CSVDescription)

Is it possible to have a Python class decorator with arguments?

What I'd like to do is this:
#add_cache(cache_this, cache_that, cache_this_and_that)
class MyDjangoModel(models.Model):
blah
But fails because it seems that the first argument is implicitly the actual class object. Is it possible to get around this or am I forced to use the ugly syntax as opposed to this beautiful syntax?
Your arg_cache definition needs to do something like:
def arg_cache(cthis, cthat, cthisandthat):
def f(obj):
obj.cache_this = cthis
obj.cache_that = cthat
obj.thisandthat = cthisandthat
return obj
return f
#arg_cache(cache_this, cache_that, cache_this_and_that)
...
The example assumes you just want to set some properties on the decorated class. You could of course do something else with the three parameters.
Write a callable that returns an appropriate decorator.

Categories