SoFunction
Updated on 2024-10-29

Python Object-Oriented_Inheritance and Overloading of Methods

1. Class inheritance and method overloading

The above is the definition of a class A, then by the definition of a class B, B inherits class A, so that B has the non-private attributes and methods of A.

class Washer:
  company='ZBL'
  def __init__(self,water=10,scour=2):
    self._water=water # Don't want the user to have direct access to the instance variable, you can flag it as private
    =scour
    =2000# It's the date of manufacture #
    # Attribute wrapping, wrapping the water attribute as a method, so that when the user uses water, they are actually accessing the method.
  @staticmethod # Define a static method
  def spins_ml(spins):
    return spins*0.4
    print('company:',)
    #print('year:',)# Error, static methods can't use instance attributes
  @classmethod
  def get_washer(cls,water,scour):#cls is equivalent to self in the instance method, which is called without this argument
    return cls(water,cls.spins_ml(scour))#cls stands for class name Washer, so it's not hard-coded (you don't have to change cls to change the class name, if cls is replaced by the class name, it's also correct, but if you change the name of the class, you need to change this place too)
  
  @property
  def water1(self):# If the user uses instance.water it is equivalent to accessing this method, not really accessing the property
    return self._water
  
  @
  def water1(self,water):
    if 0<water<=500:
      self._water=water
    else:
      print('set Failure!')
  @property
  def total_year(self):
    return 
  
  def set_water(self,water):
    =water    

  def set_scour(self,scour):
    =scour    

  def add_water(self):
    print('Add water:',self._water)

  def add_scour(self):
    print('Add scour:',)

  def start_wash(self):
    self.add_water()
    self.add_scour()
    print('Start wash...')
    
class WasherDry(Washer):# Create a new class that inherits from Washer #
  def dry(self):# New methods can be defined in the new class that belong only to subclasses
    print('Dry cloths...')
  def start_wash(self):# A new definition of a method in a subclass with the same name as the parent class is a method overloading
    self.add_scour()
    self.add_water()
    
if __name__=='__main__':
##  print(Washer.spins_ml (8))
##  w=Washer()
##  print(w.spins_ml(8))
##  w=Washer(200,Washer.spins_ml(8))
##  w.start_wash()
  w=WasherDry()
  w.start_wash()
  print(,)
  ()

Above this python object-oriented_detailed class inheritance and method overloading is all I have to share with you, I hope to be able to give you a reference, and I hope you support me more.