I am coding for to workout this question
Question
Using the concept of object oriented programming and inheritance, create a super class named Computer, which has two sub classes named Desktop and Laptop.
Define two methods in the Computer class named getspecs and displayspecs, to get the specifications and display the specifications of the computer.
You can use any specifications which you want.
The Desktop class and the Laptop class should have one specification which is exclusive to them for example laptop can have weight as a special specification.
Make sure that the sub classes have their own methods to get and display their special specification.
Create an object of laptop/ desktop and make sure to call all the methods from the computer class as well as the methods from the own class.
My solution for this is
class Computer:
def __init__(self, ram, gfx, backlit):
self.ram = ram
self.gfx = gfx
self.backlit = backlit
def getspecs(self):
self.ram = (input('RAM: '))
self.gfx = (input('GFX: '))
self.backlit = (input('Backlit: '))
def displayspecs(self):
print('RAM: ', self.ram, 'GFX: ', self.gfx, 'Backlit: ', self.backlit)
class Laptop(Computer):
def __init__(self, weight):
self.weight = weight
def getspecs_laptop(self):
self.weight = (input('Enter Weight: '))
def displayspecs_laptop(self):
print('Weight: ', self.weight)
class Desktop(Computer):
def __init__(self, size):
self.size = size
def getspecs_desktop(self):
self.size = (input('Enter Size: '))
def displayspecs_desktop(self):
print('Size:', self.size)
Computer1 = Laptop
Computer1.getspecs(1)
Computer1.getspecs_laptop(2)
Computer1.displayspecs(3)
Computer1.displayspecs_laptop(5)
Computer1.displayspecs(4)
Computer2 = Desktop
Computer2.getspecs(6)
Computer2.getspecs_desktop(7)
Computer2.displayspecs(9)
Computer2.displayspecs_desktop(99)
OUTPUT -
"D:\Coding\Python Exercises\Ass6\venv\Scripts\python.exe" "D:/Coding/Python Exercises/Ass6/Demo1.py"
RAM: 1
Traceback (most recent call last):
File "D:/Coding/Python Exercises/Ass6/Demo1.py", line 43, in <module>
Computer1.getspecs(1)
File "D:/Coding/Python Exercises/Ass6/Demo1.py", line 9, in getspecs
self.ram = (input('RAM: '))
AttributeError: 'int' object has no attribute 'ram'
Process finished with exit code 1
What is the mistake I am doing?
What needs to be given in the parent-thesis in the defined
objects?
Computer1.getspecs(here What needs to be added?)
When I run it without giving any value in it, I get error
TypeError: getspecs() missing 1 required positional argument: 'self'
There are far too many errors in this code to give you a simple answer. However, I can help with the first few:
Most of all, you wrote a lot of code without testing any of it. As a result, you now have to fix several errors at once to get any useful output. Comment out your main program for now. Instead, test your Computer class before you try to work with a Laptop or Desktop.
You need to instantiate an object of the class. Then you can use the class methods the way you want. In particular, Computer1 = Laptop(3.5) will give you a Laptop object of some weight.
Note that each of your __init__ methods has at least one required argument. Comment those out until you get used to working with basic objects.
I hope this will allow you to make some progress with your code.
Related
First of all I apologize if I have writen some word incorrectly - English is my second language.
But anyway I've been working on an text RPG for like a week and just started on an combat system and I have all of the player and enemy statistics in clases.
This is just part of my code but it's enough. So I have made a function which levels up my character.
class player:
def __init__(self):
self.name='Hero'
self.lvl=1
self.xp=0
self.lvl_next=25
self.str=1
self.dex=1
self.int=1
def pl_level(self):
Nstr=0
Ndex=0
Nint=0
while player.xp>=player.lvl_next:
player.lvl+=1
player.xp-=player.lvl_next
player.lvl_next=round(player.lvl_next*1.5)
Nstr+=1
Ndex+=1
Nint+=1
print('Level:', player.lvl)
print('STR {} +{} DEX {} +{} INT {} +{}'.format(player.str, Nstr, player.dex, Ndex, player.int, Nint))
player.str+=Nstr
player.dex+=Ndex
player.int+=Nint
print('Exp: '+str(player.xp))
print('To the next level: {}%'.format(int((player.xp/player.lvl_next)*100)))
print('Next:', player.lvl_next)
But I don't know why it just does not work.
I've tried to simplify my code because well maybe thats how i'll find the problem. But it just keeps shoving me this error.
Traceback (most recent call last):
File "F:\2XK_\Coding\Python\Python_Battle\Ulfberht\leveling_system.py", line 99, in <module>
pl_level()
File "F:\2XK_\Coding\Python\Python_Battle\Ulfberht\leveling_system.py", line 11, in pl_level
while player.xp>=player.lvl_next:
AttributeError: type object 'player' has no attribute 'xp'
Even tho you can see that in init there is self.xp.
So how can I fix this?
Use that like self.px inside other methods or else if you want to use like that only make it player().px instead of player.px.As your class needs to be to initialized first before using any of its variables or methods.
Better to access class variables in same class by using self as good practice.
I'm a little confused by what I'm seeing in the unittest file of this Exercism exercise. These are some of the tests that are run to check the validity of my program. (You create a PhoneNumber object in the main program.)
def test_area_code(self):
number = PhoneNumber("2234567890")
self.assertEqual(number.area_code, "223")
def test_pretty_print(self):
number = PhoneNumber("2234567890")
self.assertEqual(number.pretty(), "(223) 456-7890")
def test_pretty_print_with_full_us_phone_number(self):
number = PhoneNumber("12234567890")
self.assertEqual(number.pretty(), "(223) 456-7890")
I know how to create the number attribute for my class objects, but what do number.area_code and number.pretty() mean? What makes this valid Python code? I tried just creating a value like self.number.area_code = <something here>, but that didn't work. What exactly is this called and how do I create it?
Thanks!
Edit: This is another part of the unittest file:
def test_cleans_the_number(self):
number = PhoneNumber("(223) 456-7890").number
self.assertEqual(number, "2234567890")
def test_cleans_numbers_with_dots(self):
number = PhoneNumber("223.456.7890").number
self.assertEqual(number, "2234567890")
def test_cleans_numbers_with_multiple_spaces(self):
number = PhoneNumber("223 456 7890 ").number
self.assertEqual(number, "2234567890")
Doesn't this part mean that number is an attribute? This is why I misunderstood the previously quoted section. The unittest file seems to be using number in two different ways, and I didn't catch it in the former part!
I'm currently making a simple script that let's me control multiple (32) switches and routers trough a Access server. I already made a class that initiates the serial connection
Anyway, my question is how do I use an inherited method? I have a grandparent Devices that has 2 children(Father) Router and Switches. These 2 children became father to a few children let's keep it simple with SwitchA SwitchB & RouterA. Now in Cisco devices some configurations are 'standard' but not all. Let's say I want to enter "configuration terminal" trough the serial port.
Focus:
class Devices(object):
'Grandparent Class for Cisco Devices'
def __init__(self, a):
self.__a = a
def enterConfT(self):
self.__a.send( "\r" )
self.__a.send("enable\r")
print("enabled")
self.__a.send( "config terminal\r" )
print("Entered global configuration mode.")
class Switches(Devices):
'Switches Parent?'
def __init__(self):
pass
def do_nothing_yet(self):
pass
class switchA(Switches):
'Catalyst 3850 Teletest'
def __init__(self, x):
self.__x = x
In another file I got:
y = TClasses.cisco.test.switchA(serial1)
y.enterConfT()
this gives the following exception/error(I took out file directories):
'switchA' object has no attribute '_Devices__a'
['Traceback (most recent call last):\n', ' File "/sorry_privacy/test.py", line 30, in <module>\n y.enterConfT()\n', ' File "/sorry_hehe/TClasses.py", line 24, in enterConfT\n self.__a.send( "\\r" )\n', "AttributeError: 'switchA' object has no attribute '_Devices__a'\n"]
I want to be able to keep the variables a and x private while they are pointing to the same object.
What I know from OOP and C++, Minimalise repeated code and I didn't seem to have a problem with grandparent inheritence in C++ but I know Python works differently. I also read a few Q&A but couldn't really understand what they meant. I'm a beginner Python scripter.
Thank you in advance and excuse my english.
Found the answer. Using super() in the init I can initialize from parent.
This was helpfull, as I tend to read very fast and globally.
https://www.python-course.eu/python3_inheritance.php
I've searched for an answer to this problem, but I can't find an answer, it may be too specific.
I have a simple program, my first proper program and I've created it mainly as practice:
import math
class Logs(object):
def __init__(self,a,b):
self.a = a
self.b = b
def apply_log(self):
self.a_log = math.log10(self.a)
self.b_log = math.log10(self.b)
return (self.a_log, self.b_log)
def add_log(self):
self.log_add = self.a_log + self.b_log
return self.log_add
def log_split(self):
self.log_c = self.log_add // 1
self.log_m = self.log_add % 1
return(self.log_c, self.log_m)
def result(self):
self.ex_m = 10 ** self.log_m
self.ex_v = 10 ** self.log_c
self.log_res = self.ex_m * self.ex_v
return self.log_res
lg = Logs(34,54)
#print(lg.apply_log())
#print(lg.add_log())
#print(lg.log_split())
print(lg.result())
The program runs perfectly when I uncomment out all the print statements and run them at the same time. However, if I just want to print the result for the instance and comment out the three other print statements, it throws an error:
Traceback (most recent call last):
File "python", line 33, in <module>
File "python", line 24, in result
AttributeError: 'Logs' object has no attribute 'log_m'
I don't understand why it would work when printing out the results of each method or why this would affect how the program would run.
I'll also say right now that this is the first time I've used a class (the point of the program was practice for creating a class) so I imagine the error is in the way I've created it.
Any help would be very much appreciated!
Thanks
It has to throw the AttributeError because log_m is initialized in the method log_split and used in the method result. If you call result without calling log_split before, log_m is not defined and you get the error that you are seeing. This class is designed in a way that result can only be called after log_split.
log_m is a local variable inside your log_split(self) function.
So inside the result(self) function, the log_m and log_c are two variables unknown to the function.
So you have to run log_split() first and then result().
The value of log_m is initialized in log_split method, and it is dependent on the value of log_add which is initialized in add_log method. Moreover, log_add is dependent on the value of a_log and b_log which are initialized in apply_log method. Hence, it shows the AttributeError when you comment all the three implementations of the methods.
You have to maintain the sequence of method calling, otherwise commenting any of the methods will cause the error.
I'm three weeks into learning Python, via "Learn Python the Hard Way" -- since I'm not new to programming, I've been able to progress pretty rapidly through the first half of the book, until I started to get into the OOP portion with classes and objects. Now I'm having a lot of trouble; though I think I've understood the ideas behind these object concepts, I've clearly got something obscurely wrong with my code (I'm using Python 2.7.6, which appears to be part of gcc 4.8.2, in Kubuntu 14.04, kept up to date).
I'm working on Exercise 43, trying to create an adventure game starting from the author's skeleton class definitions. I did pretty well with the first game design (using Python the way I'd have used Basic for the same task, years ago), but I've been about ten console hours trying to beat the latest error in the OOP game; I've read dozens of searched solutions (here and elsewhere) without finding anything that precisely applies. I've pared the code down as much as possible, and I'm still seeing the same error (which I'll paste after the code -- warning, this is still almost 100 lines):
# Python the Hard Way -- Exercise 43: Basic Object-Oriented Analysis and Design
# received as skeleton code, try to make it into a playable game
# my comment: Much harder than designing from scratch! Author's
# design method (or that appropriate for OOP) differs greatly from
# what I'm used to.
from sys import exit
class UserEntry (object):
def __init__(self):
pass
def get_input (self):
# initialize variable for trimmed command list
short_list = []
# accept input, break at spaces, and reverse for parsing
command = raw_input ('> ')
command_list = command.split (' ')
command_list.reverse ()
# parse command here
for i in reversed (xrange (len(command_list))):
if ((command_list [i] in a_game.act.keys()) or
(command_list [i] in a_game.obj.keys())):
short_list.append (command_list.pop())
else:
command_list.pop()
# return parsed_command
if len(short_list) == 1 and short_list[0] in a_game.act.keys():
short_list.append (' ')
return short_list
class Scene (object):
def enter(self):
pass
class Engine (object):
def __init__(self, scene_map):
self.scene_map = scene_map
self.act = {
'inventory' :self.inventory,
'look' :self.look,
}
self.obj = {
'blaster' :'',
'corridor':'',
'gothon' :'',
}
def inventory(self):
pass
def look (self):
pass
def opening_scene(self):
# introduce the "plot"
print "Game intro",
def play(self):
entry = UserEntry()
self.opening_scene()
a_map.this_scene.enter()
class CentralCorridor(Scene):
def enter(self):
print "Central Corridor"
class Map(object):
def __init__(self, start_scene):
scenes = {
'central corridor': CentralCorridor,
}
this_scene = scenes[start_scene]()
print this_scene
a_map = Map('central corridor')
a_game = Engine(a_map)
a_game.play()
When I try to run this, I get the following:
$ python ex43bug.py
<__main__.CentralCorridor object at 0x7f13383c8c10>
Game intro
Traceback (most recent call last):
File "ex43bug.py", line 89, in <module>
a_game.play()
File "ex43bug.py", line 70, in play
a_map.this_scene.enter()
AttributeError: 'Map' object has no attribute 'this_scene'
Clearly, something is preventing this_scene from being visible to other classes/methods; I just don't get what it is. I don't have indention problems (that I can see), I don't have circular imports (in fact, I'm importing only a single module, for the exit command). The first print line is generated by print this_scene within instance a_map; I should get Game intro and then Central corridor as, first, Engine.opening_scene and then CentralCorridor.enter execute -- but I never get to the latter, despite apparently successfully instantiating CentralCorridor.
I'm baffled. Why isn't a_map.this_scene visible anywhere but within Map.__init__?
this_scene is only ever a local name in Map.__init__:
def __init__(self, start_scene):
scenes = {
'central corridor': CentralCorridor,
}
this_scene = scenes[start_scene]()
print this_scene
You need to assign it to an attribute on self:
def __init__(self, start_scene):
scenes = {
'central corridor': CentralCorridor,
}
self.this_scene = scenes[start_scene]()