How to create global classes in Python (if possible)?

Suppose I have several functions for an RPG I'm working on ...

def name_of_function():
     action

and wanted to implement the ax class (see below) in each function without having to rewrite each class. How to create a class as a global class. I'm not sure if I use the correct terminology or not, but please help. It always made me refuse to create text-based RPG games. An example of a global class would be awesome!

class axe:
    attack = 5
    weight = 6
    description = "A lightweight battle axe."
    level_required = 1
    price = 10
+3
source share
4 answers

- Python - , , , . , , .

, . , , .

, , weapons.py WeaponBase, Axe Broadsword , WeaponsBase. , , ,

import weapons

. , weapons.Axe Axe, weapons.Broadsword Broadsword .. :

from weapons import Axe, Broadsword

Axe Broadsword , , , .

from weapons import *

, , . -, , , - WeaponsBase, . -, , weapons , , .

import . , , , . , , , __init__.py. .

+6

( ) Python, , , Py 2.x. , , , .

: - - , . , , , , ?

class MyCLass: pass

# one way
setattr(__builtins__, 'MyCLass', MyCLass)

# another way
import __builtin__
__builtin__.MyCLass = MyCLass
+2

, - python. , . Python 3.1, :

def get_builtins():
  """Due to the way Python works, ``__builtins__`` can strangely be either a module or a dictionary,
  depending on whether the file is executed directly or as an import. I couldn’t care less about this
  detail, so here is a method that simply returns the namespace as a dictionary."""
  return getattr( __builtins__, '__dict__', __builtins__ )

, - , Py3 , Py2. " Python X.X" python.org . , ; . , Py2.

__builtins__ thingie, , , Python. sum, max, range , . , . . , ,

G          = get_builtins()
G[ 'G' ]   = G
G[ 'axe' ] = axe

, . G , G G, G . , . , G , ( ). , , , , . , .

, , . , , : , , ( ) . , . (1) , hah!, (2) , , - , , Python import. import ; . , !

ah , : , , publish() , , , . .

, : , , , ( car s, axe, ). , .

: JSON , : , , , , , , . , .

- , , , .. , , JSON ; , . , , , . .

, . , , . - ( , , , , ..) ( , dict s). , , , , BS, ( , ).

oh , , , - JSON- , ? , ? , ( this )? , , .

+1

- singleton:

class Singleton(type):
    def __init__(cls, name, bases, dict):
        super(Singleton, cls).__init__(name, bases, dict)
        cls.instance = None

class GlobalClass(object):
    __metaclass__ = Singleton
    def __init__():
        pinrt("I am global and whenever attributes are added in one instance, any other instance will be affected as well.")
0

Source: https://habr.com/ru/post/1770982/


All Articles