Skip to content

OOP

class

class People:
  def init(self, name,age):                            # init(p1,name,age)
    self.name = name                                   # p1.name = name
    self.age = age                                     # p.age = age

  def greeting(self):                                         # greeting(p1)
    return f"hello, I am {self.name} and have {self.age}"

p1 = People ("frank", 28)
print(p1.greeting())

class with decorated

class Rectangle:
  place = "here"
  _schoolName = 'XYZ School' # protected class attribute
  schoolName = 'XYZ School' # private class attribute

  def __init(self, width, height ):
    self.width = width
    self.height = height
  @property                   # save as property
  def area(self):
    return self.width  * self.height 
  def __str__(self):             
    return f"rectangle: width:{self.width} , height: {self.height}"

  def eq(self, other):
    return self.width  == otro.width and self.height  == otro.height

  @staticmethod               # method outside the object
  def amount(value):
    return f" the amount is: {value}"
  @classmenthod               # method that uses variables from the class itself used for inheritance
  def place (cls,place ):
    return f"the place is: {cls.place}"

rect1 = Rectangle(20,80)
rect2 = Rectangle(20,80)

print(rect1.area)                            # def area
print(rect1)                                 # def str or repr 
print(f"They are equal? ->{rect1 == rect2}") # def eq
print(Rectangle.place)                       # def place

inheritance and polymorphism

class Animal:
  def init(self,name):
    self.name = name

  def speak(self):
    raise NotImplementedError("this function not has implement")
  def name(self):
    return self.name 

class Dog(Animal):
  def speak(self):
    super().name(self);
    return f"GUAU GUAU"

class Cat(Animal):
  def speak(self):
    return f" Miau!!"

def make_speak(animal):
  print(f"{animal.name} says {animal.speak()}")

c1 = Cat("kitty")
d1 = Dog("Perro")

print(c1.speak())
print(d1.speak())  
make_speak(c1)
make_speak(d1)

decorators

def mi_decorator(funct):
  def envoltura():
    print (f"Saludo en la envoltura antes de llamar a la funcion")
    funct()
    print(f"Saludo en la envoltura despues de llamra a la funcion")
  return envoltura

@mi_decorador
def saludo():
  print("saludo desde dentro de la funcion ")

saludo()

Get and Set

class Persona:
  def init(self,nombre,edad):
    self._nombre = nombre
    self._edad = edad

  @property
  def edad(self): #------------ get
    return self._edad

  @edad.setter
  def edad(self,valor): #-----------set
    if valor > 0 :
      self._edad = valor
    else:
      raise ValueError("la edad no puede ser menor que cero")

manolo = Persona("Manolo",23)
print(manolo.edad)