63 lines
2.4 KiB
Plaintext
63 lines
2.4 KiB
Plaintext
![]() |
Instance methods, i.e. methods not annotated with <code>@cassmethod</code> or <code>@staticmethod</code>, are expected to have at least one parameter. This parameter will reference the object instance on which the method is called. By convention, this first parameter is named "self".
|
||
|
|
||
|
Naming the "self" parameter differently is confusing. It might also indicate that the "self" parameter was forgotten, in which case calling the method will most probably fail.
|
||
|
|
||
|
Note also that creating methods which are used as static methods without the <code>@staticmethod</code> decorator is a bad practice because calling these methods on an instance will raise a `TypeError`. Either move the method out of the class or decorate it with <code>@staticmethod</code>.
|
||
|
|
||
|
This rule raises an issue when the first parameter of an instance method is not called "self".
|
||
|
|
||
|
|
||
|
== Noncompliant Code Example
|
||
|
|
||
|
----
|
||
|
class MyClass:
|
||
|
def send_request(request): # Noncompliant. "self" was probably forgotten
|
||
|
print("send_request")
|
||
|
|
||
|
class ClassWithStaticMethod:
|
||
|
def static_method(param): # Noncompliant
|
||
|
print(param)
|
||
|
ClassWithStaticMethod().static_method(42) # Method is available on the instance but calling it will raise a TypeError
|
||
|
----
|
||
|
|
||
|
|
||
|
== Compliant Solution
|
||
|
|
||
|
----
|
||
|
class MyClass:
|
||
|
def send_request(self, request):
|
||
|
print("send_request")
|
||
|
|
||
|
class ClassWithStaticMethod:
|
||
|
@staticmethod
|
||
|
def static_method(param):
|
||
|
print(param)
|
||
|
ClassWithStaticMethod().static_method(42)
|
||
|
----
|
||
|
|
||
|
|
||
|
== Exceptions
|
||
|
|
||
|
This rule will also accept "cls" or "mcs" as first parameter's name for metaclasses' methods.
|
||
|
|
||
|
No issue will be raised for methods called <code>\_\_init_subclass\_\_</code>, <code>\_\_class_getitem\_\_</code> or <code>\_\_new\_\_</code> as these methods' first parameter is a class.
|
||
|
|
||
|
You can also disable issues on methods decorated with a specific decorator. Add these decorators to this rule's "ignoreDecorators" parameter.
|
||
|
|
||
|
With "ignoredDecorators" set to "abstractmethod"
|
||
|
----
|
||
|
from abc import abstractmethod, ABC
|
||
|
|
||
|
class MyClass(ABC):
|
||
|
@abstractmethod
|
||
|
def method(): # No issue, even if it is better in this case to also decorate with @staticmethod
|
||
|
pass
|
||
|
----
|
||
|
|
||
|
|
||
|
== See
|
||
|
|
||
|
* Python documentation - https://docs.python.org/3.8/tutorial/classes.html#method-objects[Method Objects]
|
||
|
* PEP8 - https://www.python.org/dev/peps/pep-0008/#function-and-method-arguments[Function and Method Arguments]
|
||
|
|