Skip to content

Instantly share code, notes, and snippets.

@pazdera
Created July 21, 2011 17:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pazdera/1097711 to your computer and use it in GitHub Desktop.
Save pazdera/1097711 to your computer and use it in GitHub Desktop.
Class example in Python (compared to C++)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Class example in Python (compared to C++)
class Class:
__privateMember = 1
_protectedMember = 2
publicMember = 3
def __init__(self):
print "Class constructor called"
def __del__(self):
print "Class destructor called"
# Static method can be called without an instance.
@staticmethod
def staticMethod():
print "staticMethod() called"
# Method that can be called without an instance.
# Note the required parameter `cls' which is a
# name of the class from which it was called.
@classmethod
def classMethod(cls):
print "classMethod(%s) called" % cls
def __privateMethod(self):
print "__privateMethod() called"
def _protectedMethod(self):
print "_protectedMethod() called"
def publicMethod(self):
print "publicMethod() called"
# Some examples
if __name__ == "__main__":
# Static methods
Class.staticMethod()
Class.classMethod()
example = Class()
# Members
#print "Private member: %d" % example.__privateMember # this will fail
print "Protected member: %d" % example._protectedMember
print "Public member: %d" % example.publicMember
# Methods
#example.__privateMethod() # this will fail
example._protectedMethod()
example.publicMethod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment