-1
I would like to build a class that inherits only a few methods from the mother class, but not all. To understand what I mean, suppose I have two classes, Person
and Student
:
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def __str__(self):
return self.firstname
def name_double(self):
return 2*self.firstname
class Student(Person):
pass
if __name__ == "__main__":
person=Person("Alan", "Turing")
student=Student("William","Gosset")
print(person)
print(person.name_double())
print(student)
print(student.name_double())
My goal is for the Student class to inherit only the methods __init__
and __str__
of the Person class, but not name_double
. What I tried about the class __init__
went to use:
class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)
I thought that way the Student class would inherit only the method __init__
class Person
, but that’s not what happened. When I run the program up with proper replacement in the class Student
, the result is the same:
Alan
AlanAlan
William
WilliamWilliam
It is possible to inherit methods selectively without having to make another class?
It is possible to inherit methods selectively without having to make another class? NO! You can create a common ancestor that contains only certain methods to be inherited by all descendants. Now as you are wanting to do the modeling of student and person is strange, because it gives to understand that you want to do with what a student is not a person, because as idiotic as it may seem that my observation it affects the development of the code and sometimes even prevent the logical development forcing the use of gambiarras to continue to produce.
– Augusto Vasques
Perhaps the concept of mixins can be useful to you.
– Woss