Last active
October 9, 2020 22:14
-
-
Save etigui/3dbf1e6fb88079c2a3a39bf407f2e016 to your computer and use it in GitHub Desktop.
Python - instance, class and static methods and attributes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# https://pythonguide.readthedocs.io/en/latest/python/unix.html | |
class Test: | |
public_class_attribute = 1 | |
_protected_class_attribute = 2 | |
__private_class_attribute = 3 | |
def __init__(self): | |
self.public_instance_attribute = 4 | |
self._protected_instance_attribute = 5 | |
self.__private_instance_attribute = 6 | |
def instance_method(self): | |
self.public_instance_attribute = 7 | |
self._protected_instance_attribute = 8 | |
self.__private_instance_attribute = 9 | |
return 'instance method', self | |
@classmethod | |
def class_method(cls): | |
cls.public_class_attribute = 10 | |
cls._protected_class_attribute = 11 | |
cls.__private_class_attribute = 12 | |
return f'class method', cls | |
@staticmethod | |
def static_method(): | |
return 'static method' | |
def main(): | |
# Instance methode/attribute | |
test = Test() | |
print(test.instance_method()) | |
print(test.public_instance_attribute) | |
# Class methode/attribute | |
print(Test().class_method()) | |
print(Test().public_class_attribute) | |
# Static methode | |
print(Test().static_method()) | |
if __name__ == '__main__': | |
main() | |
# Output | |
# ('instance method', <__main__.Test object at 0x7f23e377cd00>) | |
# 7 | |
# ('class method', <class '__main__.Test'>) | |
# 10 | |
# static method |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment