I inherited a student class for my masters_student class and and all the functions are working as expected but I want to give my masters_student class another parameter called Age.
How could I do that?
class masters_student(student , age):
self.age = age
def qualify(self):
if self.Gpa > 3.0 :
print("You qualify for the masters Programme")
else:
print("you dont qualify for Masters programme")
Then it shows a error
class student:
def __init__(self, name, major, Gpa, loan):
self.name = name
self.major = major
self.Gpa = Gpa
self.loan = loan
def On_honour_roll(self):
if self.Gpa >= 3.5:
return True
else:
return False
class masters_student(student):
def qualify(self):
if self.Gpa > 3.0 :
print("You qualify for the masters Programme")
else:
print("you dont qualify for Masters programme")
Here is some documentation on [https://rhettinger.wordpress.com/2011/05/26/super-considered-super/][super].
You need to tell python how to instantiate you children class following parent one.
class master_student(student):
def __init__(self, name, major, Gpa, loan, age):
super(student, self).__init__(name, major, Gpa, loan)
self.age = age
This should work.
First, we have to get our terminology correct. I don't see where you are taking an existing function that you are inheriting and then redefining it to have additional parameters. When you code:
class masters_student(student , age):
You are specifying multiple inheritance, that is, you are saying that class masters_student inherits from both class student and from class age. But then on the next line you code:
self.age = age
which does not make too much sense.
It seems that what you are trying to do is add to your new class, masters_student, an additional data attribute named age. I can't even be sure of that because I never see in your question any code that references age; I would have thought that it would be used in method qualify. But assuming that is your intent, there are several ways of doing this depending on whether you are running Python 3 or Python 2. The simplest way, which works on either Python 2 or Python 3 would be:
class masters_student(student):
def __init__(self, name, major, Gpa, loan, age):
student.__init__(self, name, major, Gpa, loan) # initialize the base class
self.age = age
If you are running Python 3, you can also code:
class masters_student(student):
def __init__(self, name, major, Gpa, loan, age):
super().__init__(name, major, Gpa, loan) # initialize the base class
self.age = age
If you are running Python 2 (or Python 3), you can also code:
class masters_student(student):
def __init__(self, name, major, Gpa, loan, age):
super(masters_student, self).__init__(name, major, Gpa, loan) # initialize the base class
self.age = age
But, you must ensure that your base class, student in this case, inherits from class object:
class student(object):
When you use super() to initialize base classes, the base classes, too, must use super() to initialize their base and sibling classes.
Related
So for instance I have a class called Employee and I have a class method designed to raise the wage of an an Employee.
I just have issues actually getting my desired raise for the wage passed into the class method as an argument, it's baffling me.
Class module;
Class Employee:
def __init__(self, name, salary, age):
self.name = name.title()
self.salary = salary
self.age = age
def raise_wage(self, raise):
self.salary = self.salary + raise
main module;
def main():
e1 = Employee("John Smith", 50000, 42)
Employee.e1.raise_wage(500)
Passing that 500 in as an arguement is the issue, i get missing positional argument errors for the method etc.
How do I pass the argument to the class method?
Hope this makes sense.
You can't use raise. It is a reserved word.
Use class instead of Class to define a class.
Write e1.raise_wage() instead of Employee.e1.raise_wage().
class Employee:
def __init__(self, name, salary, age):
self.name = name.title()
self.salary = salary
self.age = age
def raise_wage(self, amount):
self.salary = self.salary + amount
e1 = Employee("John Smith", 50000, 42)
e1.raise_wage(500)
print(e1.salary) # output: 50500
raise is a reserved keyword used to raise an exception, change it to other name and it will work just fine.
https://www.w3schools.com/python/ref_keyword_raise.asp
raise is a reserved keyword in python for raising exception. use another name for that argument then it will work. And you already created object for Employee so no need to call function with class name again.
I want to get instance of one of subclasses when trying get instance of a superclass (parent class) depending on arguments. For example, I have parent class(I'm using python3):
class Man:
def __init__(self, name, age):
self.name = name
self.age = age
def say_hello(self):
print("Hello! My name is {}.".format(self.name))
And subclass:
class YoungMan(Man):
def say_hello(self):
print("Hey, man! Wazap?")
If age of Man less 30, I want it become YoungMan:
John = Man('John', 25)
type(John) #<class '__main__.YoungMan'>
John.say_hello() #Hey, man! Wazap?
I tried solve it with Man.__new__():
class Man:
def __new__(cls, name, age):
if age < 30:
return YoungMan(name, age)
else:
return super(Man, cls).__new__()
...
But John.say_hello() returns Hello! My name is John. So Man methods override YoungMan methods. After I tried use metaclass for Man:
class ManFactory(type):
def __call__(self, name, age):
if age < 30:
return YoungMan(name, age)
class Man(metaclass=ManFactory):
...
But it lached on ManFactory.__call__().
I understand that I can use a funtion John = get_Man(name, age) which returns right class, but it isn't so handsome. My question is about how do it like this:
John = Man('John', 25)
type(John) #<class '__main__.YoungMan'>
John.say_hello() #Hey, man! Wazap?
Brad = Man('Brad', 54)
type(Brad) #<class '__main__.Man'>
Brad.say_hello() #Hello! My name is Brad.
Not sure if this is good practice but you could set self.__class__:
class Man:
def __init__(self, name, age):
if age < 30: self.__class__ = YoungMan
self.name = name
self.age = age
def say_hello(self):
print("Hello! My name is {}.".format(self.name))
class YoungMan(Man):
def say_hello(self):
print("Hey, man! Wazap?")
a = Man("Brad", 15)
print(type(a))
>>><class '__main__.YoungMan'>
a.say_hello()
>>>Hey, man! Wazap?
The main problem with this method is that the YoungMan would still be constructed by Man.__init__() so the classes would have to be compatible. Creating a function get_man() is still the best solution.
I know this is probably a simple solution. But, it has stumped me.
I simply need to access a method of the parent class, set a variable and then return it from the child class.
class Person(object):
some code ...
def setAge(self, age):
#assumes age is an int greater than 0
#sets self's age to age (in years)
self.age = age
def getAge(self):
#assumes that self's age has been set
#returns self's current age in years
if self.age == None:
raise ValueError
return self.age
class Child(Person):
code ...
def setAge(self, age):
Person(self.name).setAge(age)
def getAge(self):
return Person(self.name).age
I have even thrown some print statements in the parent class for the setAge method and gives the correct value. But, when I try to call it form the child. It gives me a None resulting in the raise ValueError
Instance variables are attached to the object; it doesn't matter if they are set via the parent class or the child class. You don't need to define Child.setAge or Child.getAge at all.
class Child(Parent):
pass
c = Child()
c.setAge(5)
print c.getAge()
Also, don't test for equality with None; use
if self.age is None:
Trying to understand multiple inheritance.
I have created a parent class called 'Human' and from it created a child class called 'Man'. This child class inherits all attributes and methods except that the human_gender attribute is overwritten and set to 'male'. - this all works fine and as expected.
What I then tried to do it created a new child class called 'BoyChild' (from 'Man') which I hoped would inherit all of man's attributes and methods except that I wished to overwrite the age attribute to set the age to 8. This is throwing up an error.
Why is this error occurring? If I remove 'age=8' from the super().init parentheses, it inherits as normal, but I can't seem to overwrite the inherited class' attribute 'age'.
class human():
'''This is a human class'''
def __init__(self, human_gender = "unknown", age = 0,
hunger_level=0):
self.human_gender = human_gender
self.age = age
self.hunger_level = hunger_level
def setGender(self):
self.human_gender = input("Please enter human's gender:")
def setAge(self):
self.age = int(input("Please enter human's age"))
def setHunger_level(self):
self.hunger_level = int(input("Please enter human's hunger level (0-10)"))
class man(human):
'''This is a Man class'''
def __init__(self):
super().__init__(human_gender="male")
class boychild(man):
'''This is a Boychild class'''
def __init__(self):
super().__init__(age=8)
guy = boychild()
#guy.setGender()
#guy.setAge()
guy.setHunger_level()
print("The human is a: ", guy.human_gender)
print("The human is: ", guy.age)
print("The human's hunger level is: ", guy.hunger_level)
input()
The __init__ method of man doesn't accept keyword arguments at all. But since you rely on it to work, you should use them:
class man(human):
'''This is a Man class'''
def __init__(self, **kwargs):
super().__init__(human_gender="male", **kwargs)
class boychild(man):
'''This is a Boychild class'''
def __init__(self, **kwargs):
super().__init__(age=8, **kwargs)
This way you catch every argument not handled by your class and just passt it on.
The class boychild inherits the class man.
Therefore, when you call super().__init__(age=8), it refers to man.__init__, that have no arguments.
You could do something like this:
class man(human):
'''This is a Man class'''
def __init__(self, age = 0, hunger_level=0):
super().__init__(human_gender="male", age, hunger_level)
I've tried reading a few different tutorials, but I still can't figure it out. I have two simple classes. Animal and cat.
class Animal:
def __init__(self, name):
self.name = name
class Cat(Animal):
def __init___(self, age):
self.age = age
print('age is: {0}'.format(self.age))
def talk(self):
print('Meowwww!')
c = Cat('Molly')
c.talk()
Output is:
Meowwww!
The code runs, but I'm a little confused. I created an instance of the cat class with c = Cat('Molly'). So somehow by using "Molly" as an argument for the Cat() class instance, it feeds "Molly" to the original base class (Animal) instead of the Cat class instance I created? Why? So how do I feed the Cat class instance the age variable it requires?
I tried doing:
c = Cat('Molly', 10)
But it complains about too many arguments. And secondly, why doesn't the __init__ function of the Cat class get called? It should print "age is...". It just never does.
EDIT: Got it to work, thanks to Martijn Pieters! Here is the updated code (works with python3):
class Animal():
def __init__(self, name):
self.name = name
print('name is: {0}'.format(self.name))
class Cat(Animal):
def __init__(self, name, age):
super().__init__(name)
self.age = age
print('age is: {0}'.format(self.age))
def talk(self):
print('Meowwww!')
c = Cat('Molly', 5)
c.talk()
You misspelled __init__:
def __init___(self, age):
# 12 345
That's 3 double underscores at the end, not the required 2.
As such, Python won't call it as it is not the method it is looking for.
If you want to pass in both age and name, give the method another argument, then call the parent __init__ with just the name:
class Cat(Animal):
def __init__(self, name, age):
super().__init__(name)
self.age = age