瀏覽代碼

Add Auto KWArgs Class

Automatically set setters in class with kwargs passed to __init__
master
Nate Bohman 4 年之前
父節點
當前提交
1fb99792be
簽署人: Nate Bohman <natrinicle@gmail.com> GPG 金鑰 ID: C10546A54ABA1CE5
共有 1 個檔案被更改,包括 55 行新增0 行删除
  1. +55
    -0
      python_utils/kwargs_init.py

+ 55
- 0
python_utils/kwargs_init.py 查看文件

@@ -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

Loading…
取消
儲存