python - Creating a static class with no instances -


all of tutorials see online show how create classes __init__ constructor methods 1 can declare objects of type, or instances of class.

how create class (static in java) can access methods , attributes of class without having create new instances/objects?

for example:

class world:      allelems = []      def addelem(x):            allelems.append(x)  world.addelem(6) print(world.allelems) 

edit

class world(object):      allairports = []      @staticmethod     def initialize():          f = open(os.path.expanduser("~/desktop/1000airports.csv"))         file_reader = csv.reader(f)          col in file_reader:              allairports.append(airport(col[0],col[2],col[3])) 

error: name 'allairports' not defined

the pythonic way create static class declare methods outside of class (java uses classes both objects , grouping related functions, python modules sufficient grouping related functions not require object instance). however, if insist on making method @ class level doesn't require instance (rather making free-standing function in module), can using "@staticmethod" decorator.

that is, pythonic way be:

# module elements = []  def add_element(x):   elements.append(x) 

but if want mirror structure of java, can do:

# module class world(object):   elements = []    @staticmethod   def add_element(x):     world.elements.append(x) 

you can @classmethod if care know specific class (which can handy if want allow static method inherited class inheriting class):

# module class world(object):   elements = []    @classmethod   def add_element(cls, x):     cls.elements.append(x) 

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -