Python: расширение интервала и MRO для __ init __

В C # есть несколько действительно скрытых ключевых слов и функций, связанных с недокументированным классом TypedReference. Следующие ключевые слова не имеют документов:

  • __makeref
  • __reftype
  • __refvalue
  • __arglist

Примеры использования:

// Create a typed reference
int i = 1;
TypedReference tr1 = __makeref(i);
// Get the type of a typed reference
Type t = __reftype(tr1);
// Get the value of a typed referece
int j = __refvalue(tr1, int); 
// Create a method that accepts and arbitrary number of typed references
void SomeMethod(__arglist) { ...
// Call the method
int x = 1;
string y = "Foo";
Object o = new Object();
SomeMethod(__arglist(x,y,o));
// And finally iterate over method parameters
void SomeMethod(__arglist) {
    ArgIterator ai = new ArgIterator(__arglist);
while(ai.GetRemainingCount() >0)
{
      TypedReference tr = ai.GetNextArg();
      Console.WriteLine(TypedReference.ToObject(tr));
}}
10
задан 26 July 2009 в 11:27
поделиться

3 ответа

The docs for the Python data model advise using __new__:

object.new(cls[, ...])

new() is intended mainly to allow subclasses of immutable types (like int, str, or tuple) to customize instance creation. It is also commonly overridden in custom metaclasses in order to customize class creation.

Something like this should do it for the example you gave:

class C(int):

    def __new__(cls, val, **kwargs):
        inst = super(C, cls).__new__(cls, val)
        inst.a = kwargs.get('a', 0)
        return inst
7
ответ дан 3 December 2019 в 23:50
поделиться

You should be overriding "__new__", not "__init__" as ints are immutable.

3
ответ дан 3 December 2019 в 23:50
поделиться

What everyone else (so far) said. Int are immutable, so you have to use new.

Also see (the accepted answers to):

3
ответ дан 3 December 2019 в 23:50
поделиться
Другие вопросы по тегам:

Похожие вопросы: