Skip to content

Instantly share code, notes, and snippets.

@ljaraque
Last active January 17, 2021 05:12
Show Gist options
  • Save ljaraque/798d7ae669d4c775f212ba3484fdd29b to your computer and use it in GitHub Desktop.
Save ljaraque/798d7ae669d4c775f212ba3484fdd29b to your computer and use it in GitHub Desktop.
Clases e Instanciación en Python3

Classes and Instantiation Process in Python

[email protected]


1. What is object in Python?

In Python, object is the base class from which all classes inherit.

The type function in Python returns the type of the object passed as argument. Actually, type function is a sintactic sugar for checking the attribute __class__ of an object.

Thus, the type of object is:

print(type(object))
print(object.__class__)
<class 'type'>
<class 'type'>

A description of object can be obtained with the dir andhelp functions:

print(dir(object))
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
print(help(object))
Help on class object in module builtins:

class object
 |  The base class of the class hierarchy.
 |  
 |  When called, it accepts no arguments and returns a new featureless
 |  instance that has no instance attributes and cannot be given any.
 |  
 |  Built-in subclasses:
 |      async_generator
 |      BaseException
 |      builtin_function_or_method
 |      bytearray
 |      ... and 91 other subclasses
 |  
 |  Methods defined here:
 |  
 |  __delattr__(self, name, /)
 |      Implement delattr(self, name).
 |  
 |  __dir__(self, /)
 |      Default dir() implementation.
 |  
 |  __eq__(self, value, /)
 |      Return self==value.
 |  
 |  __format__(self, format_spec, /)
 |      Default object formatter.
 |  
 |  __ge__(self, value, /)
 |      Return self>=value.
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __gt__(self, value, /)
 |      Return self>value.
 |  
 |  __hash__(self, /)
 |      Return hash(self).
 |  
 |  __init__(self, /, *args, **kwargs)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |  
 |  __le__(self, value, /)
 |      Return self<=value.
 |  
 |  __lt__(self, value, /)
 |      Return self<value.
 |  
 |  __ne__(self, value, /)
 |      Return self!=value.
 |  
 |  __reduce__(self, /)
 |      Helper for pickle.
 |  
 |  __reduce_ex__(self, protocol, /)
 |      Helper for pickle.
 |  
 |  __repr__(self, /)
 |      Return repr(self).
 |  
 |  __setattr__(self, name, value, /)
 |      Implement setattr(self, name, value).
 |  
 |  __sizeof__(self, /)
 |      Size of object in memory, in bytes.
 |  
 |  __str__(self, /)
 |      Return str(self).
 |  
 |  ----------------------------------------------------------------------
 |  Class methods defined here:
 |  
 |  __init_subclass__(...) from builtins.type
 |      This method is called when a class is subclassed.
 |      
 |      The default implementation does nothing. It may be
 |      overridden to extend subclasses.
 |  
 |  __subclasshook__(...) from builtins.type
 |      Abstract classes can override this to customize issubclass().
 |      
 |      This is invoked early on by abc.ABCMeta.__subclasscheck__().
 |      It should return True, False or NotImplemented.  If it returns
 |      NotImplemented, the normal algorithm is used.  Otherwise, it
 |      overrides the normal algorithm (and the outcome is cached).
 |  
 |  ----------------------------------------------------------------------
 |  Static methods defined here:
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  __class__ = <class 'type'>
 |      type(object_or_name, bases, dict)
 |      type(object) -> the object's type
 |      type(name, bases, dict) -> a new type

None

object base class does not have neither accepts any instance attribute when called. If we try to add an instance attribute to it an error will be reaised:

object_instance = object()
print("Is object_instance an instance of onbject?\n    ", isinstance(object_instance, object))
try:
    object_instance.new_attribute = "Something"
except Exception as e:
    print("ERROR:", type(e), e)
Is object_instance an instance of onbject?
     True
ERROR: <class 'AttributeError'> 'object' object has no attribute 'new_attribute'

On the other hand, if we define a class Thing, inheriting from object class, then we will be able to add an instance to the objects that are instance of Thing:

class Thing(object):
    pass


instance_of_thing = Thing()
instance_of_thing.name = "This is the name of our thing"
print(instance_of_thing.name)
This is the name of our thing
print(dir(type))
['__abstractmethods__', '__base__', '__bases__', '__basicsize__', '__call__', '__class__', '__delattr__', '__dict__', '__dictoffset__', '__dir__', '__doc__', '__eq__', '__flags__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__instancecheck__', '__itemsize__', '__le__', '__lt__', '__module__', '__mro__', '__name__', '__ne__', '__new__', '__prepare__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasscheck__', '__subclasses__', '__subclasshook__', '__text_signature__', '__weakrefoffset__', 'mro']

2. What is type in Python?

print(type(type))
print(type.__class__)
<class 'type'>
<class 'type'>

References

  1. https://eli.thegreenplace.net/2012/04/16/python-object-creation-sequence
  2. https://amir.rachum.com/blog/2016/10/03/understanding-python-class-instantiation/
  3. https://www.tutorialspoint.com/How-to-retrieve-source-code-from-Python-objects
  4. https://www.geeksforgeeks.org/python-type-function/

Content under development:

class Ser(object):
class Persona:
    
    def __new__(cls, nombre):
        instance = super().__new__(cls)
        print(dir(instance), id(instance))
        return instance
    
    def mostrar():
        print(id())
        
persona = Persona.__call__("Luis")
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'mostrar'] 140685260673952
persona = Persona("Luis")
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'mostrar'] 140685260674336
persona.mostrar()
140685260702288
class Adulto(Persona):
    pass
Adulto.__mro__
(__main__.Adulto, __main__.Persona, object)
class Mayor(Adulto):
    pass
Mayor.__mro__
(__main__.Mayor, __main__.Adulto, __main__.Persona, object)
help(type)
Help on class type in module builtins:

class type(object)
 |  type(object_or_name, bases, dict)
 |  type(object) -> the object's type
 |  type(name, bases, dict) -> a new type
 |  
 |  Methods defined here:
 |  
 |  __call__(self, /, *args, **kwargs)
 |      Call self as a function.
 |  
 |  __delattr__(self, name, /)
 |      Implement delattr(self, name).
 |  
 |  __dir__(self, /)
 |      Specialized __dir__ implementation for types.
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __init__(self, /, *args, **kwargs)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |  
 |  __instancecheck__(self, instance, /)
 |      Check if an object is an instance.
 |  
 |  __repr__(self, /)
 |      Return repr(self).
 |  
 |  __setattr__(self, name, value, /)
 |      Implement setattr(self, name, value).
 |  
 |  __sizeof__(self, /)
 |      Return memory consumption of the type object.
 |  
 |  __subclasscheck__(self, subclass, /)
 |      Check if a class is a subclass.
 |  
 |  __subclasses__(self, /)
 |      Return a list of immediate subclasses.
 |  
 |  mro(self, /)
 |      Return a type's method resolution order.
 |  
 |  ----------------------------------------------------------------------
 |  Class methods defined here:
 |  
 |  __prepare__(...)
 |      __prepare__() -> dict
 |      used to create the namespace for the class statement
 |  
 |  ----------------------------------------------------------------------
 |  Static methods defined here:
 |  
 |  __new__(*args, **kwargs)
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  __abstractmethods__
 |  
 |  __dict__
 |  
 |  __text_signature__
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  __base__ = <class 'object'>
 |      The base class of the class hierarchy.
 |      
 |      When called, it accepts no arguments and returns a new featureless
 |      instance that has no instance attributes and cannot be given any.
 |  
 |  
 |  __bases__ = (<class 'object'>,)
 |  
 |  __basicsize__ = 880
 |  
 |  __dictoffset__ = 264
 |  
 |  __flags__ = 2148293632
 |  
 |  __itemsize__ = 40
 |  
 |  __mro__ = (<class 'type'>, <class 'object'>)
 |  
 |  __weakrefoffset__ = 368
print(id(object))
objeto = object()
print(id(objeto))
class Cosa(object):
    pass
cosa=Cosa()
cosa.nombre = "Luis"
objeto.nombre = "Luis"
11444160
140685316639392



---------------------------------------------------------------------------

AttributeError                            Traceback (most recent call last)

<ipython-input-91-d19c2ab777dc> in <module>
      6 cosa=Cosa()
      7 cosa.nombre = "Luis"
----> 8 objeto.nombre = "Luis"


AttributeError: 'object' object has no attribute 'nombre'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment