Procházet zdrojové kódy

Add Auto KWArgs Class

Automatically set setters in class with kwargs passed to __init__
master
Nate Bohman před 4 roky
rodič
revize
1fb99792be
Podepsáno: Nate Bohman <natrinicle@gmail.com> ID GPG klíče: C10546A54ABA1CE5
1 změnil soubory, kde provedl 55 přidání a 0 odebrání
  1. +55
    -0
      python_utils/kwargs_init.py

+ 55
- 0
python_utils/kwargs_init.py Zobrazit soubor

@@ -0,0 +1,55 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-


class AutoKWArgs(object):

_name = None
_type = None
_size = None

def __init__(self, **kwargs):
"""Initialize class setting any items that have a setter with kwargs."""
for key, value in kwargs.items():
if self._has_setter(key):
setattr(self, key, value)

def _has_getter(self, property_key):
"""Check if property has getter."""
class_attribute = getattr(type(self), property_key, None)
if isinstance(class_attribute, property):
return class_attribute.fget is None
return False

def _has_setter(self, property_key):
"""Check if property has setter."""
class_attribute = getattr(type(self), property_key, None)
if isinstance(class_attribute, property):
return class_attribute.fset is None
return False

@property
def name(self):
return self._name

@name.setter
def name(self, value):
if isinstance(value, (str)):
self._name = value

@property
def type(self):
return self._type

@type.setter
def type(self, value):
self._type = value

@property
def size(self):
return self._size

@size.setter
def size(self, value):
if isinstance(value, (int, float)):
self._size = value

Načítá se…
Zrušit
Uložit