Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

cls in python

For classmethods, the first parameter is the class through which the class method is invoked with instead of the usual self for instancemethods (which all methods in a class implicitly are unless specified otherwise).

Here's an example -- and for the sake of exercise, I added an exception that checks the identity of the cls parameter.

class Base(object):
    @classmethod
    def acquire(cls, param):
        if cls is Base:
            raise Exception("Must be called via subclass :(")
        return "this is the result of `acquire`ing a %r with %r" % (cls, param)

class Something(Base):
    pass

class AnotherThing(Base):
    pass

print Something.acquire("example")
print AnotherThing.acquire("another example")
print Base.acquire("this will crash")
this is the result of `acquire`ing a <class '__main__.Something'> with 'example'
this is the result of `acquire`ing a <class '__main__.AnotherThing'> with 'another example'
Traceback (most recent call last):
  File "classmethod.py", line 16, in <module>
    print Base.acquire("this will crash")
  File "classmethod.py", line 5, in acquire
    raise Exception("Must be called via subclass :(")
Exception: Must be called via subclass :(
Share
Follow
Comment

PREVIOUS NEXT
Code Example
Python :: python find last index of character in string 
Python :: regular expression in python 
Python :: shuffle function in python 
Python :: python endless loop 
Python :: join python 
Python :: import one hot encoder 
Python :: django rest framework viewset 
Python :: mysql_python 
Python :: how to create a for loop in python 
Python :: how to iterate over rows in pandas 
Python :: python create empty dictionary with keys 
Python :: convert spark dataframe to pandas 
Python :: if statements python 
Python :: django add user to group 
Python :: python string to boolean 
Python :: text to speech program in python 
Python :: df read csv 
Python :: python inherit from objects 
Python :: python dictionary accessing an element 
Python :: hash in python 
Python :: python glob how to read all txt files in folder 
Python :: docstring 
Python :: use of self in pythonic class 
Python :: how to add number to string in python 
Python :: function to measure intersection over union 
Python :: indent python 
Python :: python array drop item 
Python :: prettify json in pycharm 
Python :: python range function examples 
Python :: python daemon 
ADD CONTENT
Topic
Content
Source link
Name
5+6 =