Is it ever useful to use a class method with a reference to self, not called "I" in Python?

I teach Python, and I see the following in Dive into Python section 5.3 :

By convention, the first argument of any Python class method (reference to the current instance) is called self. This argument fills the role of the reserved word thisin C ++ or Java, but is selfnot a reserved word in Python, but simply a naming convention. However, please do not call it anything but self; this is a very strong agreement.

Given that selfit is not a Python keyword, I assume that it is sometimes useful to use something else. Are there any such cases? If not, why is this not a keyword?

+3
source share
6 answers

The only case I've seen is when you define a function outside the class definition and then assign it to the class, for example:

class Foo(object):
    def bar(self):
        # Do something with 'self'

def baz(inst):
    return inst.bar()

Foo.baz = baz

In this case, it’s a selflittle strange to use, because this function can be applied to many classes. Most often I saw instead instor cls.

+4
source

Not unless you want to confuse any other programmer who watches your code after writing it. selfis not a keyword because it is an identifier. It could be a keyword, and the fact that this is not one was a constructive solution.

+9
source

, Pilgrim : - , . wikipedia , " - , ( ) ( ).". Python staticmethod classmethod , ; , a def . :.

>>> class X(object):
...   def noclass(self): print self
...   @classmethod
...   def withclass(cls): print cls
... 
>>> x = X()
>>> x.noclass()
<__main__.X object at 0x698d0>
>>> x.withclass()
<class '__main__.X'>
>>> 

, noclass , withclass .

, self : cls, . , - , , , number_of_cats, ! -)

+5

- - ( - ):

class Animal:
    def __init__(self, volume=1):
        self.volume = volume
        self.description = "Animal"

    def Sound(self):
        pass

    def GetADog(self, newvolume):
        class Dog(Animal):
            def Sound(this):
                return self.description + ": " + ("woof" * this.volume)
        return Dog(newvolume)

:

>>> a = Animal(3)
>>> d = a.GetADog(2)
>>> d.Sound()
'Animal: woofwoof'

, self Dog self Animal, Dog "this". -, .

+2

, self , Python, /, , , , ..

, (.. classmethod), "cls" "self".

+1

Because it is a convention, not a language syntax. There is a Python style guide followed by people who program in Python. Thus, libraries have a familiar look. Python places a lot of emphasis on readability, and consistency is an important part of this.

+1
source

Source: https://habr.com/ru/post/1714530/


All Articles