Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm studying Python programming and I'm having difficulty understanding Inheritance. My assignment is to:
Create a Division and Department class.
Create a method named “getList()” which will display a message, “The
dept department has fullTime full-time and partTime part-time
instructors.”
In the “Department” class, assign 12 as value to the fullTime
variable, assign 27 to partTime, and “CIS” to dept. DO NOT create
any method in the “Department” class. and
Create an instance (object) of the “Department” class named
“myDept”. Use this “myDept” object to call the “getList()” method of
“Division” class (through Inheritance).
Here's what I have so far.
class Division():
def __init__(self, dept, fullTime, partTime):
self.dept = dept
self.fullTime = fullTime
self.partTime = partTime
def getList(self):
return "The (0) department has (1) full-time and (2) part-time instructors.".format(self.dept, self.fullTime, self.partTime)
class Department(Division):
myDept = Division(CIS247, 12, 27)
class Division(object):
def __init__(self,dept, fullTime, partTime):
self.fullTime = fullTime
self.partTime = partTime
self.dept=dept
def getList(self):
return "The {0} department has {1} full-time and {2} part-time instructors.".format(self.dept, self.fullTime, self.partTime)
class Department(Division):
pass
myDept = Department("CIS",12,37)
print myDept.getList()
Edited, I missed the "CIS", for string formatting you use {} not ().
Also " DO NOT create any method in the “Department” class." so removed init method.
python classes tutorial
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I am trying to create an object and I'm initializing it with 2 fields first (name & number). However each time I run the program I'm given this error:
TypeError: __init__() missing 1 required positional argument: 'number'
The __init__ method in the class looks like this:
def __init__(self, name, number):
self.__name__ = name
self.__number__ = number
The code where I try to create the object is this:
employee1 = ProductionWorker(Employee)
name = input("Enter employee name:")
number = input("Enter employee number:")
employee1.__init__(name, number)
Does anyone know why I may be getting this error?
Do:
name = input("Enter employee name:")
number = input("Enter employee number:")
employee1 = ProductionWorker(name, number)
You do not generally need to call __init__ explicitly; it's invoked by the ProductionWorker(...) expression, which passes its arguments to self.__init__ as part of initialization.
You do not need to restate when constructing a new object that Employee is the parent class; that only needs to be said when the class is defined.
You are using the class as a parameter.
Then, init is always automatically called on creation. This how it might work as You want (using the show method to validate):
class Employee:
def __init__(self, name, number):
self.__name__ = name
self.__number__ = number
def show(self):
print(self.__name__)
print(self.__number__)
name = input("Enter employee name:")
number = input("Enter employee number:")
employee1 = Employee(name,number)
employee1.show()
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I need to create new class by type function.
def create_fk_widget_from_model(model, **kwargs):
to_field = kwargs.pop('to_field', 'id')
rel = ManyToOneRel(None, model, to_field) # type: ignore
return type(
f'{model.__name__}ForeignKeyRawIdWidget',
(ForeignKeyRawIdWidget, ),
{'__init__': ForeignKeyRawIdWidget.__init__(
rel=rel,
admin_site=admin.site)}
)
But there is a problem. I need to change __init__ in new class, how to do it?
You probably want something like:
def create_fk_widget_from_model(model, **kwargs):
to_field = kwargs.pop('to_field', 'id')
rel = ManyToOneRel(None, model, to_field) # type: ignore
def __init__(self):
return ForeignKeyRawIdWidget.__init__(self, rel=rel, admin_site=admin.site)
return type(
f'{model.__name__}ForeignKeyRawIdWidget',
(ForeignKeyRawIdWidget, ),
{'__init__': __init__}
)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I want to add the age for users in a different method but some users might not have an age argument
class User:
"""a class to save info about every user """
def __init__(self, user_name, num_id):
self.name = name
self.mun_id = num_id
def age(self, age):
self.age = age
user1 = User("martin", "1")
print (user1.name)
Yes you can set user age separately. Example below:
user1.age(20)
print (user1.age)
#20 will print
define age = None like below and this optional argument should be the last one:
def age(self, age = None):
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I'm struggling to figure out how to organize things here.
I'm building a race game. There are players and race courses. Player have attributes like name, age, etc. Race courses also have a set of attributes, including difficulty. One thing I want to do is, when a player runs a course their energy level drops based on difficulty of the course. What I'm confused about is, because difficulty is an attribute of the course, and energy level is an attribute of the player, how can I affect the two?
Take the code for example...
class Player():
energy_level = 0
def __init__(self, name, ability)
self.name = name
self.ability = ability
def run(self):
#code to run course here, reduces energy level when running course. Energy level is reduced based on player ability
class Course():
def __init__(self, name, difficulty)
self.name = name
self.difficulty = difficulty
player1 = Player("Bob", 90)
course1 = Course("Advanced Track", 15)
Maybe I am going about this all wrong? Does course need to be a class?
Thanks for any input.
How can I affect the two?
This you can achieve by passing an object of type Course to the run function like so:
class Player():
energy_level = 0
def __init__(self, name, ability)
self.name = name
self.ability = ability
def run(self, course):
#use course.difficulty to reduce self.energy_level
class Course():
def __init__(self, name, difficulty)
self.name = name
self.difficulty = difficulty
player1 = Player("Bob", 90)
course1 = Course("Advanced Track", 15)
player1.run(course1) # this will pass course1 to the run function and run will reduce the energy level according to the difficulty of course1
You can make course a member of the player class
class Player():
course = null;
energy_level = 0
def __init__(self, name, ability)
self.name = name
self.ability = ability
self.course1 = Course("Advanced Track", 15)
def run(self):
#code to run course here, reduces energy level when running course. Energy level is reduced based on player ability
#change self.energy based on self.course1.difficulty
Of course this is an oversimplification. You need to add methods to open new courses, and not hardcode this in the constructor.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
Write a program to store student details in a class. The information should include a
studentnumber, first name, surname and username.
Include a function that returns the e-mail address of the student. You construct the emaila ddress by adding "#coventry.ac.uk" to the username. So, Joe Blogs, with username
blogsj would get the e-mail address blogsj#coventry.ac.uk
2 Task 2
Create a program that uses the class from task 1 to collect a list of student records from
the user and allow them to be listed, with e-mail addresses.
You should include a menu system for the user.
#Python Lab9 Task1 & Task2
class student(object):
def _init_(self,student_ID,name,surname,username):
self.student_ID = student_ID
self.name = name
self.surname = surname
self.username = username
def email(self):
return self.username, "#coventry.ac.uk"
def _str_(self):
return "%d %s %s %s"%(self.student_ID,self.name,self.surname,self.username)
if __name__ == '__main__':
students=[]
user=""
while user not in ["Q","q"]:
print "Menu"
print "1. Show student detail"
print "2. Create new student detail"
print "3. Quit"
user=raw_input(">")
if user=="1":
for i in students:
print i
elif user=="2":
print "Creating a new student detail"
print "-----------------------------"
student_ID=raw_input("Student ID:")
name=raw_input("First Name:")
surname=raw_input("Surname:")
username=raw_input("Username:")
s = student(student_ID,name,surname,username)
students.append(s)
elif user=="3":
exit
You need double underscores for __init__ and __str__:
class student(object):
def __init__(self,student_ID,name,surname,username):
...
def __str__(self):
Here is a reference.
Also, exit won't work unless you invoke it by placing () after it:
elif user=="3":
exit()
Finally, because self.student_ID will be a string, you need to replace the %d on this line with %s:
return "%s %s %s %s"%(self.student_ID,self.name,self.surname,self.username)
%d is only used for integers.