Learning Python


In [19]:
# Let's create some code for fun
# Character, Status classes

from sys import getsizeof

In [8]:
class Character:
    
    __slots__ = ['_name', '_level', '_profession']
    
    def __init__(self, name, level, profession):
        self._name = name
        self._level = level
        self._profession = profession
        
    @property
    def level(self):
        return self._level
    
    @level.setter
    def level(self, level):
        if level >= 0:
            self._level = level
        else:
            print('Level cannot be negative.')
    
    @property
    def name(self):
        return self._name
    
    @name.setter
    def name(self, name):
        self._name = name
    
    @property
    def profession(self):
        return self._profession
    
    @profession.setter
    def profession(self, profession):
        self.profession = profession

In [14]:
cha1 = Character('Character 01', 10, 'Magician')
cha2 = Character('Character 02', 11, 'Magician')

In [20]:
class CharacterWithoutSlots:
    
    def __init__(self, name, level, profession):
        self._name = name
        self._level = level
        self._profession = profession
        
    @property
    def level(self):
        return self._level
    
    @level.setter
    def level(self, level):
        if level >= 0:
            self._level = level
        else:
            print('Level cannot be negative.')
    
    @property
    def name(self):
        return self._name
    
    @name.setter
    def name(self, name):
        self._name = name
    
    @property
    def profession(self):
        return self._profession
    
    @profession.setter
    def profession(self, profession):
        self.profession = profession

In [21]:
cha1 = Character('Character 01', 10, 'Magician')
cha2 = CharacterWithoutSlots('Character 01', 10, 'Magician')

getsizeof(cha1), getsizeof(cha2)


Out[21]:
(64, 56)

In [32]:
class Example:
    def __getattr__(self, attr):
        return attr.upper()
    
    def __getattribute__(self, attr):
        __dict__ = super(Example, self).__getattribute__('__dict__')
        
        if attr in __dict__:
            return super(Example, self).__getattribute__(attr)
        
        return attr.upper()

        
d = Example()
d.value = 'Python'

In [35]:
d.does_not_exist


Out[35]:
'DOES_NOT_EXIST'

In [36]:
d.value


Out[36]:
'Python'

In [ ]: