An instance method decorator that also works as a classmethod.
Project description
This simple module creates a class method that will also work as an instance method.
import dynamicmethod
class Example(object):
x = 1 # Default classmethod value
def __init__(self, x=0):
self.x = x
@dynamicmethod
def get_x(self):
return self.x
print(Example.get_x())
ex = Example()
print(ex.get_x())
ex.x = 5
print(ex.get_x())
I have grown to use this module quite a bit. Mostly I make a default class level dictionary where each instance can be customized.
from dynamicmethod import dynamicmethod
class Lookup(object):
lookup_type = {'type1': 1, 'mytype2': 2}
def __init__(self):
# Save an instance variable so the class variable does not change.
self.lookup_type = self.__class__.lookup_type.copy()
@dynamicmethod
def add_type(self, name, value):
self.lookup_type[name] = value
@dynamicmethod
def get_type(self, name):
return self.lookup_type.get(name, None)
Lookup.add_type('New Type', 3)
print(Lookup.get_type('New Type'))
specific_lookup = Lookup()
print(specific_lookup.get_type('New Type'))
specific_lookup.add_type('hello', 'world!')
print(specific_lookup.get_type('hello'))
# print(Lookup.get_type('hello')) # This would be None since the class lookup does not contain 'hello'
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
dynamicmethod-1.0.4.tar.gz
(4.3 kB
view hashes)
Built Distribution
Close
Hashes for dynamicmethod-1.0.4-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 927a7b7c7d78c571dd8246b49f75a815739f4da09d06721aceece79be2c47fcd |
|
MD5 | 694ae2ea7c1e7dfdcadab421d944af34 |
|
BLAKE2b-256 | c380f5735389a122cf3add04d71a00f2daf061dd070892b194886c29a347b626 |