English 中文(简体)
How do I fix PyDev "Method should have self as first parameter" errors
原标题:

I m developing in Python using PyDev in Eclipse, and some of my code generates errors in the code analysis tool. Specifically:

class Group(object):
    def key(self, k):
        class Subkey(object):
            def __enter__(s):
                self._settings.beginGroup(k)
                return self

            def __exit__(s, type, value, tb):
                self._settings.endGroup()

         return Subkey()

Gives me a "Method __enter__- group should have self as first parameter" error, and a similar error for __exit__. Is there a way to solve this without assigning self to another variable and reusing the variable in the other method signatures?

最佳回答

You could disable that error in the preferences...

Window > Preferences > Pydev > Editor > Code Analysis > Others

Or refactor the code...

class Group(object):
    def key(self, k):
        outer_self = self
        class Subkey(object):
            def __enter__(self):
                outer_self._settings.beginGroup(k)
                return outer_self

            def __exit__(self, type, value, tb):
                outer_self._settings.endGroup()

         return Subkey()

What else do you expect? The error checks are there to help you. If you don t think they re legitimate errors, disable them or refactor the code.

In this case I d say refactor the code. It s more readable, as evidenced by King Radical s answer. He didn t understand that s was another self.

问题回答

Using Ctrl+1 in a line with an error from PyDev will always bring you a fix which will allow you to ignore the PyDev error in the line. In this specific case, it ll allow you to ignore the error by adding #@NoSelf to the end of the line. Ctrl+1 is also useful when some unused import is needed and under other situations.

You can use a decorator:

class aClass:
        def __init__(self):       # instance-dependent method
        self.atribite1 = []
        self.atribute2 = 0 

        @staticmethod   
        def static():             # static method
        pass

The Built-in function used for this

It shouldn t be an error in the first place, as using "self" is only a widely-accepted convention. It should be a warning at most, in the sense of "are you sure you re using the class instance as the first argument?"

IMO this is a silly warning. the name "self" is only convention. I got the habit of using the name "_" to allow the member names to be more obvious,

class myClass( object ):
    def __init__( _, color, shape, weight ):
        _.color=color
        _.shape=shape
        _.weight=weight
...

and I get this warning all over my library of thousands of lines of code. So I ll be switching this warning off. Would be nice to be able to specify "for this project I use _ by convention"...

PyDev is telling you that Python class methods must have self as the first variable they receive, if they re going to access the class member variables. See: http://www.python.org/doc/faq/general/#why-must-self-be-used-explicitly-in-method-definitions-and-calls

Edit: It didn t initially occur to me that you might be using s instead of self, but in view of the other answers, that may be. However, if you re going to do that, you also need to use s as your variable in the method, rather than self.





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签