metaclass

Python: Passing the default values of function' arguments to *args or **kwargs

耗尽温柔 提交于 2020-01-11 09:32:42
问题 Consider example: def decorator(func): def wrapper(*args, **kwargs): print(args, kwargs) func(*args, **kwargs) return wrapper @decorator def foo(x, y, z=0): pass foo(5, 5) Output: (5, 5) {} Why not (5, 5) {'z': 0} ? How to pass all default values of the function foo to *args or **kwargs using only decorator (for functions) or metaclass (for class methods, e.g. __init__ )? 回答1: The wrapper is just a normal function. It does not have "access" to the internals of the wrapped function. You would

Python, mixing PyQt5 and abc.ABCMeta

本小妞迷上赌 提交于 2020-01-10 06:04:26
问题 I am trying to create an AbstractClass using both abc.ABCMeta and QObject as parents and cannot seems to make it work. Here is the Base class init. I have Pyqt5 and python 2.7 pyqtWrapperType = type(QObject) class ParamsHandler(abc.ABCMeta, pyqtWrapperType): def __init__(self, device_model, read_only=False): super(ParamsHandler, self).__init__() self.cmd_to_get_data = None self.device_model = device_model class ConfigParamsHandler(ParamsHandler): def __init__(self, device_model): super

Reverse mapping class attributes to classes in Python

半世苍凉 提交于 2020-01-07 06:40:34
问题 I have some code in Python where I'll have a bunch of classes, each of which will have an attribute _internal_attribute . I would like to be able to generate a mapping of those attributes to the original class. Essentially I would like to be able to do this: class A(object): _internal_attribute = 'A attribute' class B(object): _internal_attribute = 'B attribute' a_instance = magic_reverse_mapping['A attribute']() b_instance = magic_reverse_mapping['B attribute']() What I'm missing here is how

Get attributes for class and instance in python

ぐ巨炮叔叔 提交于 2020-01-04 03:12:23
问题 In python work next code: class MyClass(object): field = 1 >>> MyClass.field 1 >>> MyClass().field 1 When I want return value for custom fields I use next code: class MyClass(object): def __getattr__(self, name): if name.startswith('fake'): return name raise AttributeError("%r object has no attribute %r" % (type(self).__name__, name)) >>> MyClass().fake fake But: >>> MyClass.fake Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: class MyClass has no

Arguments of __new__ and __init__ for metaclasses

霸气de小男生 提交于 2020-01-03 19:14:15
问题 I am a bit surprised by the method call order and the different arguments when overriding new and init in a metaclass. Consider the following: class AT(type): def __new__(mcs, name, bases, dct): print(f"Name as received in new: {name}") return super().__new__(mcs, name + 'HELLO', bases + (list,), dct) def __init__(cls, name, bases, dct): print(f"Name as received in init: {name}") pass class A(metaclass=AT): pass A.__name__ The output is: Name as received in new: A Name as received in init: A

UML metamodel: derived, derived union and subsetting

随声附和 提交于 2020-01-03 08:29:09
问题 If you have ever worked with the metamodel of UML, you propably know the concepts of unions and subsets - As far as I understand it: Attributes and associations of an element/class marked as " derived union " cannot be used directly. In more specific sub-classes, you can possibly find subsets of them that can be used, as long as they are not marked as derived unions themselves. " derived " (without union) attributes and associations have also subsets in more specific classes, but unlike above

TypeErrors using metaclasses in conjunction with multiple inheritance

可紊 提交于 2020-01-01 14:56:39
问题 I have two questions converning metaclasses and multiple inheritance. The first is: Why do I get a TypeError for the class Derived but not for Derived2 ? class Metaclass(type): pass class Klass(object): __metaclass__ = Metaclass #class Derived(object, Klass): pass # if I uncomment this, I get a TypeError class OtherClass(object): pass class Derived2(OtherClass, Klass): pass # I do not get a TypeError for this The exact error message is: TypeError: Error when calling the metaclass bases Cannot

How different is type.__setattr__ from object.__setattr__?

我与影子孤独终老i 提交于 2020-01-01 04:45:10
问题 type.__setattr__ is used for classes, basically instances of metaclasses. object.__setattr__ on the other hand, is used for instances of classes. This is totally understood. I don't see a significant difference between the two method, at least at Python level, I notice the two use the same procedures for attribute assignment, correct me if I'm wrong: Suppose a is an instance of a user-defined class, just a normal class: class A: pass a = A() a.x = ... then a.x = .. invokes type(a).__setattr__

Dynamically adding methods with or without metaclass

时光毁灭记忆、已成空白 提交于 2020-01-01 04:28:06
问题 Update - 2012/12/13 Just to clarify - I'm not so much interested in ways how to add methods to classes - as you can see below in my question and in people's answers, there is more than one way to do that (tongue in cheek and hat tip to my Perl self). The thing I am interested in is learning what's the fundamental difference of adding methods to classes using different approaches and the big question really is why do I need to use metaclasses for. For example A Primer on Python Metaclass

SqlAlchemy metaclass confusion

徘徊边缘 提交于 2020-01-01 04:16:06
问题 I'm trying to inject some of my own code in the class construction process of SqlAlchemy. Trying to understand the code, I'm somewhat confused by the implementation of the metaclass. Here are the relevant snippets: The default "metaclass" of SqlAlchemy: class DeclarativeMeta(type): def __init__(cls, classname, bases, dict_): if '_decl_class_registry' in cls.__dict__: return type.__init__(cls, classname, bases, dict_) else: _as_declarative(cls, classname, cls.__dict__) return type.__init__(cls