AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / user-16969525

Cornélio Sousa's questions

Martin Hope
Cornélio Sousa
Asked: 2024-06-28 06:26:42 +0800 CST

Comportamento de object.__new__ Python dunder. O que está acontecendo sob o capô?

  • 9

Estou experimentando metaprogramação em Python (CPython 3.10.13) e notei algum comportamento estranho object.__new__(bem, estranho para mim, pelo menos). Dê uma olhada no experimento a seguir (não é um código prático, apenas um experimento ) e nos comentários. Observe que object.__new__parece mudar seu comportamento com base no primeiro argumento:

# Empty class inherit __new__ and __init__ from object
class Empty:
    pass

# Confirmation of inheritance
assert Empty.__new__ is object.__new__, "Different __new__"
assert Empty.__init__ is object.__init__, "Different __init__"

empty_obj = Empty()
uinit_empty_obj = object.__new__(Empty)

assert type(empty_obj) is type(uinit_empty_obj), "Different types"

try:
    object.__new__(Empty, 10, 'hi', hello='bye')
except TypeError as e:
    # repr(e) mentioned the Empty class
    print(repr(e))

# Overwrite the object __new__ and __init__ methods
# __new__ and __init__ with the same signature
class Person:
    def __new__(cls, name, age):
        """Does nothing bassicaly. Just overwrite `object.__new__`."""
        print(f'Inside {cls.__name__}.__new__')
        return super().__new__(cls)
    
    def __init__(self, name, age):
        print(f'Inside {type(self).__name__}.__init__')
        self.name = name
        self.age = age

a_person = Person('John Doe', 25)
uinit_person = Person.__new__(Person, 'Michael', 40)

try:
    # Seems an obvious error since object() doesn't take any arguments
    another_uinit_person = object.__new__(Person, 'Ryan', 25)
except TypeError as e:
    # Indeed raises TypeError, but now there isn't a mention of the Person class in repr(e)
    print('`another_uinit_person` :', repr(e))

# Now, some weird things happen (well, weird for me).
# Inherit __new__ from object and overwrite __init__.
# __new__ and __init__ with unmatching signatures.
# A basic Python class. Works just fine like suppose to.
class Vehicle:
    def __init__(self, model):
        self.model = model

# Confirmation of __new__ inheritance.
assert Vehicle.__new__ is object.__new__, "Nop, it isn't"

a_vehicle = Vehicle('Honda')

# I would understand if CPython autogenerated a __new__ method matching __init__
# or a __new__ method that accepts all arguments.
# The following try-except-else suggests the last, but the assert statement above 
# indicates that Vehicle.__new__ is actually object.__new__.
try:
    # Doesn't raise any exceptions
    uinit_vehicle = Vehicle.__new__(Vehicle, 'Honda', 10, ('four-wheels',), hello='bye')
except Exception as e:
    print(repr(e))
else:
    print('`uinit_vehicle` : constructed just fine', uinit_vehicle)

# Now the following runs just fine
try:
    # Doesn't raise any exceptions
    another_unit_vehicle = object.__new__(Vehicle, 'Toyota')
    another_unit_vehicle = object.__new__(Vehicle, 'Toyota', 100, four_wheels=True)
except Exception as e:
    print(repr(e))
else:
    print('`another_unit_vehicle` : constructed just fine:', another_unit_vehicle)

Eu obtive a seguinte saída:

TypeError('Empty() takes no arguments')
Inside Person.__new__
Inside Person.__init__
Inside Person.__new__
`another_uinit_person` : TypeError('object.__new__() takes exactly one argument (the type to instantiate)')
`uinit_vehicle` : constructed just fine <__main__.Vehicle object at 0x00000244D15A7A90>
`another_unit_vehicle` : constructed just fine: <__main__.Vehicle object at 0x00000244D15A7A30>

Minhas perguntas:

  1. Por que o primeiro TypeErrormencionou a Emptyturma e o segundo apenas object.__new__?
  2. Por que object.__new__(Person, 'Ryan', 25)levantou TypeErrore object.__new__(Vehicle, 'Toyota')não object.__new__(Vehicle, 'Toyota', 100, four_wheels=True)fez?

Basicamente: o que object.__new__acontece por baixo do capô?

Parece-me que ele está realizando uma verificação um tanto estranha nos métodos do primeiro argumento __new__e/ou __init__substituição, se houver.

python
  • 1 respostas
  • 50 Views

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Reformatar números, inserindo separadores em posições fixas

    • 6 respostas
  • Marko Smith

    Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não?

    • 2 respostas
  • Marko Smith

    Problema com extensão desinstalada automaticamente do VScode (tema Material)

    • 2 respostas
  • Marko Smith

    Vue 3: Erro na criação "Identificador esperado, mas encontrado 'import'" [duplicado]

    • 1 respostas
  • Marko Smith

    Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores?

    • 1 respostas
  • Marko Smith

    Como faço para corrigir um erro MODULE_NOT_FOUND para um módulo que não importei manualmente?

    • 6 respostas
  • Marko Smith

    `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso?

    • 3 respostas
  • Marko Smith

    Um programa vazio que não faz nada em C++ precisa de um heap de 204 KB, mas não em C

    • 1 respostas
  • Marko Smith

    PowerBI atualmente quebrado com BigQuery: problema de driver Simba com atualização do Windows

    • 2 respostas
  • Marko Smith

    AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos

    • 1 respostas
  • Martin Hope
    Fantastic Mr Fox Somente o tipo copiável não é aceito na implementação std::vector do MSVC 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant Encontre o próximo dia da semana usando o cronógrafo 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor O inicializador de membro do construtor pode incluir a inicialização de outro membro? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul O C++20 mudou para permitir a conversão de `type(&)[N]` de matriz de limites conhecidos para `type(&)[]` de matriz de limites desconhecidos? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann Como/por que {2,3,10} e {x,3,10} com x=2 são ordenados de forma diferente? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller O ponto e vírgula agora é opcional em condicionais bash com [[ .. ]] na versão 5.2? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench Por que um traço duplo (--) faz com que esta cláusula MariaDB seja avaliada como verdadeira? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng Por que `dict(id=1, **{'id': 2})` às vezes gera `KeyError: 'id'` em vez de um TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos 2024-03-20 03:12:31 +0800 CST

Hot tag

python javascript c++ c# java typescript sql reactjs html

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve