create account

Python Tricks #3 by boyanpro

View this thread on: hive.blogpeakd.comecency.com
· @boyanpro ·
$0.04
Python Tricks #3
```python



# @classmethod vs @staticmethod vs "plain" methods
# What's the difference?

class MyClass:
    def method(self):
        """
        Instance methods need a class instance and
        can access the instance through `self`.
        """
        return 'instance method called', self

    @classmethod
    def classmethod(cls):
        """
        Class methods don't need a class instance.
        They can't access the instance (self) but
        they have access to the class itself via `cls`.
        """
        return 'class method called', cls

    @staticmethod
    def staticmethod():
        """
        Static methods don't have access to `cls` or `self`.
        They work like regular functions but belong to
        the class's namespace.
        """
        return 'static method called'

# All methods types can be
# called on a class instance:
>>> obj = MyClass()
>>> obj.method()
('instance method called', <MyClass instance at 0x1019381b8>)
>>> obj.classmethod()
('class method called', <class MyClass at 0x101a2f4c8>)
>>> obj.staticmethod()
'static method called'

# Calling instance methods fails
# if we only have the class object:
>>> MyClass.classmethod()
('class method called', <class MyClass at 0x101a2f4c8>)
>>> MyClass.staticmethod()
'static method called'
>>> MyClass.method()
TypeError: 
    "unbound method method() must be called with MyClass "
    "instance as first argument (got nothing instead)"

```
👍  , , , , , , , , , , , , , , , ,
properties (23)
authorboyanpro
permlinkpython-tricks-3
categoryprogramming
json_metadata{"community":"busy","app":"busy/2.5.6","format":"markdown","tags":["programming","python","coding","pytricks","dev"],"users":["classmethod","staticmethod"],"links":[],"image":[]}
created2019-04-19 09:44:48
last_update2019-04-19 09:44:48
depth0
children0
last_payout2019-04-26 09:44:48
cashout_time1969-12-31 23:59:59
total_payout_value0.032 HBD
curator_payout_value0.007 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length1,449
author_reputation2,328,945,471,331
root_title"Python Tricks #3"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id83,376,790
net_rshares80,454,461,300
author_curate_reward""
vote details (17)