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.
Related
Looking at the code I have below as an example. Why is it I get the error "Float object not callable" when using print statement 1 but not print statement 2? what do I need to do to my class if I was wanting to make print statement 1 work?
var1 = float(input())
class ExampleClass(object):
def __init__(self, thing1):
self.getThing1 = thing1
def getThing1(self):
return self.getThing1
a = ExampleClass(var1)
print(str(a.getThing1())) #print statement 1 that doesn't work
print(str(a.getThing1)) #print statement 2 that does work
You are trying to use getThing1 as a method name and an attribute. You declare a method getThing1, but then you assign self.getThing1 = thing1. So getThing1 isn't a method anymore; it's the value of thing1.
Perhaps you meant this:
class ExampleClass(object):
def __init__(self, thing1):
self.thing1 = thing1
def getThing1(self):
return self.thing1
However, getXXX methods are not the convention in Python. If you need a method wrapping your attribute, you should make it a property.
This:
class ExampleClass(object):
def __init__(self, thing1):
---> self.getThing1 = thing1
shadows this:
def getThing1(self):
return self.getThing1
Python functions are objects don't live in a distinct namepsace, so to make a long story short you cannot have an attribute and a method by the same name.
The solution is simple: don't use getThing1 as an attribute name - specially since "get" is a verb so it's a poor name for a value.
Also note that Python has a string support for computed attributes so you don't need systematic getters/setters for attributes. You can start with a plain attribute and turn it into a computed one later if the need arises.
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)
Doing a class and finished with the rest less this one. Any guidance is appreciated. I have derived part of the question where I am stuck with to keep it short. I have also attached my working. Question as follows:
Create a class with 1 variable in it holding its own properties.
Provide the following 3 methods:
getvariable1() - use return key tp return value of property 1
setvariable1() - This should allow new value to be specified for property 1 - additional parameter needed to accept input.
printerfun() - to print values of the variables for the object.
Create your own object of the class and call get & set methods for the object created. Use printerfun() method to check if the codes works.
My working:
class animal:
horns = 2
def printerfun(self):
print getHorns()
def getHorns(self): #don't get where I should call this
return self.horns
def setHorns(horns):
self.horns = horns
animal_1 = animal()
F1 = raw_input('Please enter number of horns: ')
setHorns(F1)
Not sure what the question is, but anyway...
You should write a __init__ member function to create the initial member variables:
class animal:
def __init__(self):
self.horns = 2
Your code creates a class variable, not a normal member variable.
Then change the horns with:
animal_1.setHorns(F1)
Your code doesn't say which animal you want to change the variable to.
I have been having trouble getting python to generate a (non-predetermined) number of class instances. Basically have classes be able to reproduce themselves.
class foo:
def __init__(self, name):
self.name = name
while True:
newinstance(foo) #what would the code be for this?
#or maybe
foo.newinstance #just something that could update itself
Basically generate a new instance any number of times. Thanks ahead of time.
This will do what you're asking for, but you'll want to hold onto the values somehow:
while True:
foo(some_name)
This will loop forever, so a more realistic option might be:
names = ["Ned", "Felix", "Guy"]
fooses = [foo(name) for name in names]
Use a list comprehension:
instances_of_foo = [foo("bar") for i in range(number_of_instances)]
Also, if you would like to pass different arguments to each instance, you can create of list of args instead of using range().
list_of_args = [args_for_instance_one, args_for_instance_two,...]
instances_of_foo = [foo(arg) for arg in list_of_args]
Using python.....I have a list that contain names. I want to use each item in the list to create instances of a class. I can't use these items in their current condition (they're strings). Does anyone know how to do this in a loop.
class trap(movevariables):
def __init__(self):
movevariables.__init__(self)
if self.X==0:
self.X=input('Move Distance(mm) ')
if self.Vmax==0:
self.Vmax=input('Max Velocity? (mm/s) ')
if self.A==0:
percentg=input('Acceleration as decimal percent of g' )
self.A=percentg*9806.65
self.Xmin=((self.Vmax**2)/(2*self.A))
self.calc()
def calc(self):
if (self.X/2)>self.Xmin:
self.ta=2*((self.Vmax)/self.A) # to reach maximum velocity, the move is a symetrical trapezoid and the (acceleration time*2) is used
self.halfta=self.ta/2. # to calculate the total amount of time consumed by acceleration and deceleration
self.xa=.5*self.A*(self.halfta)**2
else: # If the move is not a trap, MaxV is not reached and the acceleration time is set to zero for subsequent calculations
self.ta=0
if (self.X/2)<self.Xmin:
self.tva=(self.X/self.A)**.5
self.halftva=self.tva/2
self.Vtriang=self.A*self.halftva
else:
self.tva=0
if (self.X/2)>self.Xmin:
self.tvc=(self.X-2*self.Xmin)/(self.Vmax) # calculate the Constant velocity time if you DO get to it
else:
self.tvc=0
self.t=(self.ta+self.tva+self.tvc)
print self
I'm a mechanical engineer. The trap class describes a motion profile that is common throughout the design of our machinery. There are many independent axes (trap classes) in our equipment so I need to distinguish between them by creating unique instances. The trap class inherits from movevariables many getter/setter functions structured as properties. In this way I can edit the variables by using the instance names. I'm thinking that I can initialize many machine axes at once by looping through the list instead of typing each one.
You could use a dict, like:
classes = {"foo" : foo, "bar" : bar}
then you could do:
myvar = classes[somestring]()
this way you'll have to initialize and keep the dict, but will have control on which classes can be created.
The getattr approach seems right, a bit more detail:
def forname(modname, classname):
''' Returns a class of "classname" from module "modname". '''
module = __import__(modname)
classobj = getattr(module, classname)
return classobj
From a blog post by Ben Snider.
If it a list of classes in a string form you can:
classes = ['foo', 'bar']
for class in classes:
obj = eval(class)
and to create an instance you simply do this:
instance = obj(arg1, arg2, arg3)
EDIT
If you want to create several instances of the class trap, here is what to do:
namelist=['lane1', 'lane2']
traps = dict((name, trap()) for name in namelist)
That will create a dictionary that maps each name to the instance.
Then to access each instance by name you do:
traps['lane1'].Vmax
you're probably looking for getattr.