Created
July 21, 2011 17:32
-
-
Save pazdera/1097711 to your computer and use it in GitHub Desktop.
Class example in Python (compared to C++)
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
#!/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