Search code examples
python-3.xclassparametersselfclass-instance-variables

Class Inheritance python require fill child class name


it might be a silly question since I'm new to Python. However, I hope someone can explain this because I try to find lots of resource but still hardly understand the mechanism behind.

So I create a Parent Class and a Child Class. Parent Class have set_name, get_name method

In Child Class, I defined a new method call Turn_Uppercase which calling get_name then uppercase the name. And when using Turn_Uppercase Method, I have to filled in Child Class Name, otherwise it would not work.

Can someone explain the mechanism here!

Let's me explain in code:

So first I create a Parent Class with get_name and set_name method.

class Parent:
    def __init__(self, text_input):
        self.__name = "" 
        self.name = text_input
    
    @property    #this is get_name
    def name(self):
        return self.__name 
    
    @name.setter    #this is set_name
    def name(self, text_input: str):
        if isinstance(text_input, str): # check input has to be string
            self.__name = text_input
        else:
            print('Wrong type of data')

Then I create a Child Class with new method called Turn_uppercase

class Child_to_parent(Parent):
    def __init__(self):
        pass
    def turn_uppercase(self):
        return self.name.upper()  

Now I put in some object and use Turn_uppercase Method, I have to fill in Child Class Name

test1 = Child_to_parent
test1.name = "abcdef" # using parent method
print(f'{test1.turn_uppercase(Child_to_parent)}') # using child method

When using parent method through property name, I don't need to declare Child Class Name, but when it comes to use Turn_uppercase Method then I have to.

Why it works this way?


Solution

  • This line makes all the difference

    test1 = Child_to_parent
    

    You are not creating an object here, instead merely assigning a reference to the class itself. What you must be doing is

    test1 = Child_to_parent() #>Create the object!
    test1.name = "abcdef"
    print(f'{test1.turn_uppercase()}')
    

    Now why it works with the class? It's because you attached a attribute to the class called name. The method you called used the class as argument and evaluated the class attribute!

    Read this answer for a better understanding!