0

is more than anything a doubt but, I want to create a class that put in memory methods a single time and then instances that believes it can share these methods without these have to be put in memory for each one of them.

juancarlos
  • 593
  • 3
  • 9

1 Answers1

0

Methods are "put in memory" only once. Methods are sequences of bytecode instructions and will be stored only once. However, properties (methods operate on) are not.

I think, you are confusing the difference of class properties and object properties. Use them as shown in the following examples:

class Foo:
    def __init__(self):
        self.object_prop = None

    def set(self, val):
        self.object_prop = val

    def get(self):
        return self.object_prop

Then you can use it like this:

a = Foo()
a.set(3)
print(a.get())  # prints 3
b = Foo()
b.set(4)
print(a.get())  # prints 3

And the class properties example looks like this:

class Foo:
    class_prop = None

    @classmethod
    def set(cls, val):
        cls.class_prop = val

    @classmethod
    def get(cls):
        return cls.class_prop

a = Foo()
a.set(3)
print(a.get())  # prints 3
b = Foo()
b.set(4)
print(a.get())  # prints 4

Maybe this is, what you are looking for.

In the comments, you pointed out that you are looking for an implementation of singletons in python. In python, singletons are an anti-pattern and need to be avoided at all costs. However, a simple search on StackOverflow gives the following result:

class Singleton(type):
    _instances = {}
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]

class Logger(metaclass=Singleton):
    pass

With this implementation, all objects will have the same memory address:

>>> id(Logger())
140202032740616
>>> id(Logger())
140202032740616
meisterluk
  • 804
  • 10
  • 19
  • I refer to something as a singleton, an example I create my first object and it is loaded into memory, then when I created other objects of the same class instead of being loaded the whole object in memory this could use the methods that were already in memory of the first object – juancarlos Jun 23 '18 at 23:37
  • i = "" i2 = "" print(i.index) print(i2.index) _____output_____ might be something like this are two objects different but methods point to the same area memory – juancarlos Jun 23 '18 at 23:45
  • Methods are attached to objects. If two objects are the same, they will use the same methods. So in essence, you mean the singleton pattern, yes. But as you did not explain your usecase, I cannot tell how you came up with your wrong conclusion that you need singletons. Singletons always mean bad design in python. – meisterluk Jun 24 '18 at 00:29