How do I add a Method to a Class to modify an attribute of an Object and also assign a default value if nothing is given

  oop, python

This is a problem which I have to solve. I have spend roughly 4 hours in this part.
I can’t work out how to set a "Default" to the owner attribute and to add a method to change the owner attribute.

The instructions given are as follows

File may have other attributes such as owner. If not indicated, the
owner will be set to “default”. Implement a method chown(new_owner)
that will allow you to modify the owner of a file or directory.

My code


#Main class, which other files will inherit from
class File:
    
    owner="default"
   
   
        
    
    
class Directory (File):
    
    
    def __init__(self,name,right):
        self.name=name
        self.right=right
    
    def chown (self,new_owner):
        self.new_owner=new_owner
        File.owner=new_owner
        
  
    
    def __str__(self):
        return "Directory({},{})".format(self.name,self.right)
    def __repr__(self):
        return "Directory({},{})".format(self.name,self.right)
        
  

class PlainFile(File):
    
    
    def __init__(self,filename):
        self.filename=filename
    
    def chown (self,new_owner):
        self.new_owner=new_owner
        File.owner=new_owner
        
   
    def __str__ (self):
        return "PlainFile ({})".format (self.filename)
    
    
    def __repr__ (self):
        return "PlainFile ({})".format (self.filename)
    

Below is the expected code and the correct answers

>> file = PlainFile("boot.exe")
>> folder = Directory("Downloads",[])
>> print(f'file.owner: {file.owner}; folder: {folder.owner}')
file.owner: default; folder: default
>> file.chown("root")
>> folder.chown("isaac")
>> print(f'file.owner: {file.owner}; folder: {folder.owner}')
file.owner: root; folder: isaac

Source: Python Questions

LEAVE A COMMENT