Skip to content

Instantly share code, notes, and snippets.

@RDCH106
Created December 3, 2019 11:47
Show Gist options
  • Save RDCH106/6c92b16d57ea2d08b778e3f232155de2 to your computer and use it in GitHub Desktop.
Save RDCH106/6c92b16d57ea2d08b778e3f232155de2 to your computer and use it in GitHub Desktop.
Python Class Prototype (Example) - Scope: Private, Public, Internal, Static
# -*- coding: utf-8 -*-
from random import randint
class MyClass(object):
# Static class variable
static_variable = 17
def __init__(self, property_a, property_b=11):
self.__property_a = property_a # Private
self.property_b = property_b # Public
self._property_c = "Internal property of the class" # Internal
@property
def property_a(self):
return self.__property_a
@property_a.setter
def property_a(self, value):
self.__property_a = value
@staticmethod
def print_hello(name=None):
print("Hello!" if name is None else "Hello {name}!".format(name=name))
@staticmethod
def random_number_from_0_to_10():
return randint(0, 10)
def print_class_values(self):
print("Class properties: PropA=[{prop_a}] PropB=[{prop_b}] propC=[{prop_c}]".format(
prop_a=self.__property_a,
prop_b=self.property_b,
prop_c=self._property_c
)
)
# Try MyClass
if __name__ == "__main__":
print("Static variable: {}".format(MyClass.static_variable))
MyClass.print_hello()
MyClass.print_hello("RDCH106")
print("Random number from 0 to 10: {}".format(MyClass.random_number_from_0_to_10()))
my_class = MyClass(property_a=5)
my_class.print_class_values()
public_prop_b = 12
print("Set public property B to {}".format(public_prop_b))
my_class.property_b = public_prop_b
my_class.print_class_values()
private_prop_a = 7
print("Set private property A to {}".format(private_prop_a))
my_class.property_a = private_prop_a
my_class.print_class_values()
print("Get private property A to {}".format(my_class.property_b))
# Internal variables of the class are also available. But be careful, are internal!
internal_prop_a = "Internal property C modified!"
print("Get internal property C: {}".format(my_class._property_c))
my_class._property_c = internal_prop_a
print("Set internal property C to \"{}\"".format(my_class._property_c))
my_class.print_class_values()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment