class Temperature():
def convertF(self,c):
return c*1.8+32
def convertC(self,f):
return (f-32)*(5/9)
c=float(input())
f=float(input())
n_temp=Temperature(c)
n_temp=Temperature(f)
print(n_temp.convertF)
print(n_temp.convertC)
I've creating a class Temperature, then I created 2 methods one for converting Celsius to Fahrenheit and another for converting the latter to former.
Now I want to take the values of Celsius and Fahrenheit from user but I'm getting the error :
Temperature() takes no arguments.
Can someone tell me what I'm doing wrong?
If you want to use Temperature(<value>), you need a constructor. Once you have a constructor, your other methods dont need parameters
class Temperature():
def __init__(self, temp):
self.temp = temp
def convertF(self):
return self.temp * 1.8 + 32
def convertC(self):
return (self.temp-32)*(5/9)
n_temp=Temperature(float(input()))
print(n_temp.convertC()) # you need to call the function
Or you can use static methods if you don't want to use a constructor (since the constructor itself doesn't know if the input is in Celcius, Farenheit, or Kelvin), but then you would need to remove the argument from the class initialization, and pass it to the functions
# call a static method
print(Temperature.convertC(0)) # 32
Temperature (the class) doesn't take any arguments; each of its methods does take an argument.
Related
In Python, is there a simple way for an invoked function to get a value from the calling function/class ? I'm not sure if I'm phrasing that right, but I'm trying to do something like this:
class MainSection(object):
def function(self):
self.var = 47 # arbitrary variable
self.secondaryObject = secondClass() # Create object of second class
self.secondaryObject.secondFunction(3) # call function in that object
and
class secondClass(object):
def secondFunction(self, input)
output = input + self.var # calculate value based on function parameter AND variable from calling function
return output
#Access self.var from MainSection
This might be my lack of knowledge about Python, but I'm having a hard time finding a clear answer here. Is the best way to do that just passing the variable I want in as another second parameter to the second class?
These are in separate files, if that makes a difference.
Is the best way to do that just passing the variable I want in as another second parameter to the second class?
Yes, especially if there's only a transient relationship between the objects:
class secondClass(object):
def secondFunction(self, input, var_from_caller)
output = input + var_from_caller # calculate value based on function parameter AND variable from calling function
return output
You can even pass around the whole object if you like:
class secondClass(object):
def secondFunction(self, input, calling_object)
output = input + calling_object.var # calculate value based on function parameter AND variable from calling function
return output
If the relationship is more permanent, you could consider storing references to the related objects in instance variables:
class MainSection(object):
def function(self):
self.var = 47 # arbitrary variable
self.secondaryObject = secondClass(self) # Create object of second class
self.secondaryObject.secondFunction(3) # call function in that object
...
class secondClass(object):
def __init__(self, my_friend):
self.related_object = my_friend
def secondFunction(self, input)
output = input + self.related_object.var # calculate value based on function parameter AND variable from calling function
return output
#Access self.var from MainSection
class bread:
def __init__(self,grain,cost,number):
self.grain=(grain)
self.cost=int(cost)
self.number=int(number)
def price(self):
p=self.cost*self.number
print(p)
apple=bread("wholemeal",int(2),int(12))
print(apple.grain,apple.cost,apple.number)
print (apple.price)
After I enter this block of code I should expect to see 24, but instead I get:
bound method bread.price of <main.bread object at 0x05CC7430>>
I am new to oop and starting to experiment but I can't find a solution.
You need to call price:
apple.price()
However, variable attribute behavior with methods can be achieved using property:
class bread:
def __init__(self,grain,cost,number):
self.grain=grain
self.cost=cost
self.number=number
#property
def price(self):
return self.cost*self.number
apple=bread("wholemeal",2, 12)
print(apple.price)
In this case you don't seem to want to deal with a class object, but just want to get the output. This you can do like so:
class bread:
def __init__(self, grain, cost, number):
self.grain = (grain)
self.cost = int(cost)
self.number = int(number)
return self.price()
def price(self):
p = self.cost * self.number
print("%s : %d" % (self.grain, p))
bread("wholemeal", 2, 12)
As a beginner you should not worry too much about things like property but keep it as simple (and verbose) as possible. Also because you're making the input for the grain type, I'm guessing you want to print that out together with the value.
To unpack the changes I made to your code as an example for some basic coding practices:
note the spacing between functions
note the spacing between individual items
note how the output is produced with print()
Once all this is done, all we have to do is make the call we would otherwise have to make ourselves everytime, inside __init__. Good luck, and have fun learning python!
When you print the function at the end, you actually need to call the function. Currently you are just getting the instance of the method within the object. But you should be using parenthesis () to call the function when you print it. You also don't need to print the function call to get 24 since you are already printing the output of number and cost within your function. But if you do want to print the function, you can use a return value within your function. Here is an example below:
class bread(object):
def __init__(self, grain, cost, number):
self.grain = grain
self.cost = cost
self.number = number
def price(self):
price = self.cost * self.number
return price
apple=bread("wholemeal", 2, 12)
print(apple.price())
Notice that at the end of the code We actually called the function () when printing it. You will then print the return value of the function. If you wanted to simply print the value within the function, you could call the function at the bottom of the code without printing it like this:
apple.price()
and then choose to put the print statement within the price method. Your output from the code above it 24:
24
So, I have defined the following class which should resemble a probability mass function. However, its logic seems broken and it will raise SUM_ERROR every time I try to initialize a new object.
class ProbabilityMass(dict):
class InvalidEntries(Exception):
pass
SUM_ERROR = InvalidEntries("all values must add upto '1'")
VAL_ERROR = InvalidEntries("negative values are not allowed")
def __init__(self, pm):
dict.__init__(pm)
# Input requirements
if not self.sumsUptoOne():
raise ProbabilityMass.SUM_ERROR
if not self.isNonnegative():
raise ProbabilityMass.VAL_ERROR
def isNonnegative(self):
return all(d < 0 for d in self.values())
def sumsUptoOne(self):
return sum(self.values()) == 1
How can I fix this?
Calling dict.__init__() does not initialize the class. The correct call to super should look like this:
def __init__(self, pm):
super(ProbabilityMass, self).__init__(pm)
# Input requirements
...
As a side note, your isNonnegative() method is also incorrect. Change it to:
def isNonnegative(self):
return all(d >= 0 for d in self.values())
Usually, when dict.__init__() is called, it is because you used dict(). When a class is called like a function, an instance is created, and the instance's .__init__() method is called with the arguments given to the class. Well, calling an instance method is the same thing as calling the class method with the instance as a first argument. Therefore, x = dict() is short for:
x = new dict instance
dict.__init__(x)
If you already have an instance of dict (or a subclass) that was not initialized, you can call __init__() yourself. You must, however, remember to pass the instance as the first argument:
dict.__init__(self, pm)
The more common way is to use the built-in super():
super(ProbabilityMass, self).__init__(pm)
In one of our homework problems, we need to write a class in python called Gate which contains the drawing and function of many different gates in a circuit. It describes as follows:
in1 = Gate("input")
out1 = Gate("output")
not1 = Gate("not")
Here in1, out1, not1 are all instances of this class. What do the ("input") ("output") ("not") mean? are they subclass or something?
We are only told that when we define a class using:
class Gate(object)
when we make an instance we use:
in1 = Gate()
I haven't seen stuff inside a () after the class name, how to understand that?
Taking into account that you pass strings as a parameter I would suggest that it is just a parameter like:
class Gate:
def __init__(self, param1):
self.param1 = param1
var1 = Gate("hello")
print var1.param1
# expected output:
# hello
To be able to say how the class Gate works one has to look into it.
What is in1 = Gate("input") this?
In short this Gate("input") is a constructor call def init.
Use for create object.
Gate() and Gate("some value") both are constructor but
1). Gate() Create a object without initialize value to particular attributes of this object.
2). Gate('some value') Create a object with a value.
And i think you need to work on some basic concept of OOPS.
I am trying to make a text based game using Python. I set up a radar() function but currently the only way to use it is if the player types in arguments directly to the console. I want the program to detect which vehicle the player is piloting and pass whatever attributes of that vehicle need to be passed automatically without the player having to type them.
For example
Instead of the player having to type in
'a.radar([100,100,100], 100)' in order to use the radar() function I want the player to only need to type in 'radar', and all other parameters to be passed automatically. How can I make this happen? Should I restructure this code entirely?
My code:
class Mobilesuits:
#class global variables/methods here
instances = [] #grid cords here
def __init__(self,armor,speed,name,description,cockpit_description,\
radar_range, coordinates):
Mobilesuits.instances.append(self)
self.armor=armor
self.speed=speed
self.name=name
self.description=description
self.cockpit_description=cockpit_description
self.radar_range=radar_range
self.coordinates=coordinates
def radar(self, coordinates, radar_range):
for i in range(len(a.instances)):
cordcheck=a.instances[i].coordinates
if cordcheck == coordinates:
pass
elif (abs(cordcheck[0]-coordinates[0]) <= radar_range) and \
(abs(cordcheck[1]-coordinates[1]) <= radar_range) and \
(abs(cordcheck[2]-coordinates[2]) <= radar_range):
print("%s detected at %s ") %(a.instances[i].description, a.instances[i].coordinates)
a=Mobilesuits(100,100,"Leo","leo desc","dockpit desc",100,[100,100,100])
b=Mobilesuits(100,100,"Leo","leo desc","dockpit desc",100,[300,100,100])
c=Mobilesuits(100,100,"Leo","leo desc","dockpit desc",100,[100,150,100])
a.radar([100,100,100], 100)
Have your program take input with the raw_input function:
user_input = raw_input()
and then do something based on the input:
if user_input == "some_command":
do_something(appropriate, variables)
For example,
if user_input == "radar":
a.radar([100,100,100], 100)
You might also want to change the way the radar method takes arguments. It looks like at least one of the coordinates or the radar_range arguments should be coming from the corresponding attributes of self. For example, if a mobile suit's radar should automatically use the mobile suit's own coordinates and radar range, you could write the method as follows:
def can_detect(self, other):
for own_coord, other_coord in zip(self.coordinates, other.coordinates):
if abs(own_coord - other_coord) > self.radar_range:
return False
return True
def radar(self):
for other in Mobilesuits.instances:
if other is not self and self.can_detect(other):
print "%s detected at %s" % (other.description, other.coordinates)
Do it like builtins do.
Look, str() function is just specialized call to __str__ function. object class has default __str__, and if you're not using p3k, str() has some logic for objects without __str__.
In the end, str() builtin MAY look like this (conceptually, implementation is probably quite different):
def str(obj):
try:
return obj.__str__()
except AttributeError:
return default_behaviour(obj)
You can do something alike.
You'll need function which will return user object (say there are 3 players in the game: A, B and C, where A is controlled by user; you'll need function get_user_player() which shall return A instance.
Then, you need to implement your argumentless radar function:
def radar():
return get_user_player().radar()
Now call to radar() will result in automatic finding of user controlled instance and calling radar on it.