I don't know how to interact between classes - python-2.7

If I have this two classes:
class bandido:
def __init__(self, vida, ataque):
self.vida = random.randint(40,81)
self.ataque = random.randint(15,46)
class xiaoling:
def __init__(self, vida, ataque):
self.vida = 100
self.ataque = 100
How can I make a fight? and see who wins?

Related

Python - Overriding a parent variable with a getter/setter

So I have a parent class BaseAdd that I'm trying to subclass. The BaseAdd uses self.left and self.right, I want to use self.nodes to make it easier to access both left and right at once:
class BaseAdd():
def __init__(self, leftright):
self.left = leftright[0]
self.right = leftright[1]
class Add(BaseAdd):
def __init__(self, leftright):
self.nodes = leftright
#property
def left(self):
return self.nodes[0]
#left.setter
def left(self, value):
self.nodes[0] = value
foo = Add(('L', 'R'))
foo.left = "new"
print(foo.left, foo.nodes[0])
>>> ('new', 'L')
The problem is that the setter is never getting called, my hunch is that it's using the BaseAdd.left somehow instead. How can I make the setter properly set the list element?

Underlying class changes between serialisation and deserialisation

There is an object of testclass created at some point in the life of program and then it is serialized in file system using pickle or h5py. Now during this period the definition of testclass is updated. The update is always about adding new fields (and not removing existing ones).
Does deserializing the stored class back and referencing it using updated testclass definition a right approach?
Before Serialization: Class is defined
class testclass:
__fieldA = None
__fieldB = None
__fieldC = 'Hello'
def __init__(self, A, B):
self.__fieldA = A
self.__fieldB = B
def setA(self, A):
self.__fieldA = A
def getA(self):
return self.__fieldA
def setB(self, B):
self.__fieldB = B
def getB(self):
return self.__fieldB
def setC(self, C):
self.__fieldC = C
def getC(self):
return self.__fieldC
>>>orig_obj = testclass('testA', 'testB')
>>>isinstance(orig_obj, testclass)
>>>True
>>>with open('test', 'wb') as handle:
pickle.dump(orig_obj, handle, protocol=pickle.HIGHEST_PROTOCOL)
After Serialization: Class definition is changed
class testclass:
__fieldA = None
__fieldB = None
__fieldC = 'Hello'
__fieldD = 10
def __init__(self, A, B):
self.__fieldA = A
self.__fieldB = B
def setA(self, A):
self.__fieldA = A
def getA(self):
return self.__fieldA
def setB(self, B):
self.__fieldB = B
def getB(self):
return self.__fieldB
def setC(self, C):
self.__fieldC = C
def getC(self):
return self.__fieldC
def setD(self, D):
self.__fieldD = D
def getD(self):
return self.__fieldD
>>>with open('test', 'rb') as handle:
loaded_obj = pickle.load(handle)
>>>isinstance(loaded_obj, testclass)
>>>False
Now loaded_obj is not an instance of testclass. This makes sense and has nothing to do with the fact whether new field __fieldD is introduced or not.
In this scenario, what is the best way to ensure that loaded_obj is an instance of testclass?

Django multiple model update/create

I am a beginning programmer in Django/Python and I am now looking for a way to robustly create and update my models. I would expect this is a very common problem. Some example code of how to do this the right way would be very much appreciated.
Problems which I struggling with is that I am not sure where to put the save() command. Now there are multiple places where I put the save() method. And sometimes I have to multiple times hit the save button on the various views before a change on a low level trickless up to a higher level model.
In this example I use two simplified models named Medium and Circuit. The create methods for the two models are specified as well as a set_medium and set_circuit method, this shows how I am currently doing it.
class Circuit(models.Model):
medium = models.ForeignKey('medium.Medium', related_name='medium_related', on_delete=models.CASCADE)
temperature = models.FloatField(default=60, help_text='[degC]')
glycol_percentage = models.FloatField(default=0, choices = choices.GLYCOL_PERCENTAGE)
#classmethod
def create( cls,
temperature,
glycol_percentage):
circuit = cls( temperature = temperature,
glycol_percentage = glycol_percentage)
circuit.medium = Medium.create(circuit.temperature, circuit.glycol_percentage)
circuit = circuit.set_circuit(circuit)
circuit.save()
return circuit
def set_circuit(self, circuit):
circuit.medium.glycol_percentage = circuit.glycol_percentage
circuit.medium.temperature = circuit.temperature
circuit.medium = circuit.medium.set_medium(circuit.medium)
return circuit
class Medium(models.Model):
glycol_percentage = models.FloatField(default=0, choices = choices.GLYCOL_PERCENTAGE)
temperature = models.FloatField(default=60, help_text='[degC]')
# Calculated properties
rho = models.FloatField(default=1000, help_text='[kg/m3]')
#classmethod
def create( cls, temperature, glycol_percentage):
medium = cls( temperature = temperature,
glycol_percentage = glycol_percentage)
medium = medium.set_medium(medium)
medium.save()
return medium
def set_medium(self, medium):
medium.rho = services.rho(temperature=medium.temperature, glycol_percentage=medium.glycol_percentage)
return medium
Below is how I typically write my Create and Update views.
class CircuitCreateView(LoginRequiredMixin, CreateView):
model = Circuit
template_name = 'circuit/create.html'
form_class = CircuitForm
def form_valid(self, form):
circuit = Circuit.create( glycol_percentage = form.cleaned_data['glycol_percentage'],
temperature = form.cleaned_data['temperature'])
circuit.save()
return HttpResponseRedirect(reverse('circuit:detail', args=(circuit.id,)))
class CircuitUpdateView(LoginRequiredMixin, UpdateView):
model = Circuit
template_name = 'circuit/detail-update.html'
form_class = CircuitForm
def form_valid(self, form):
circuit = get_object_or_404(Circuit, pk=self.kwargs['pk_circuit'])
circuit.glycol_percentage = form.cleaned_data['glycol_percentage']
circuit.temperature = form.cleaned_data['temperature']
circuit = circuit.set_circuit(circuit)
circuit.save()
return HttpResponseRedirect(reverse('circuit:detail', args=(circuit.id,)))

object inheritance arugment input error

Playing around with inheritance and came across an error stating that I am inputing too many arguments. What could I be doing wrong?
This first file is called media.py
class Video():
def __init__(self, title, duration):
self.title = title
self.duration = duration
class Movie(Video):
def __init__(self, movie_story, movie_poster, trailer_youtube):
Video.__init__(self, title, duration)
self.storyline = movie_story
self.poster_image_url = movie_poster
self.trailer_youtube_url = trailer_youtube
def show_trailer(self):
webbrowser.open(self.trailer_youtube_url)
class TvShow(Video):
def __init__(self, season, episode, tv_station):
Video.__init__(self, title, duration)
self.season = season
self.episode = episode
self.tv_station = tv_station
This second file creates the objects.
import fresh_tomatoes
import media
family_guy = media.TvShow("Family Guy",
"2000-Present",
"Fifteen Seasons",
"Twenty-Eight",
"Fox")
print family_guy.title
The terminal output states I'm passing 6 arguments when only 4 may be accepted. Why is that?
Calling the parent __init__ will only invoke it , but you still need to pass in the arguments to it.
So when you invoke __init__ method for TvShow it only expects 3 +1(self) arguments , while you were trying to send more than that. So to solve the issue you just need to increase the number of arguments excepted by the __init__.
class Video():
def __init__(self, title, duration):
self.title = title
self.duration = duration
class Movie(Video):
def __init__(self, movie_story, movie_poster, trailer_youtube):
Video.__init__(self, title, duration)
self.storyline = movie_story
self.poster_image_url = movie_poster
self.trailer_youtube_url = trailer_youtube
def show_trailer(self):
webbrowser.open(self.trailer_youtube_url)
class TvShow(Video):
def __init__(self, season, episode, tv_station, title, duration):
Video.__init__(self, title, duration)
self.season = season
self.episode = episode
self.tv_station = tv_station

Is it dangerous to define __contains__ on a metaclass?

I'm writing a custom EnumMeta class in Python 2.7 that will collect enum keys and values from some class and augment that class with some additional fields.
class EnumMeta(type):
def __init__(cls, name, bases, props):
cls.__all_values__ = [...] # collect all interesting properties
def __contains__(cls, value):
return value in cls.__all_values__
class TheFellowshipOfTheRing(object):
__metaclass__ = EnumMeta
FRODO = 'Frodo Baggins'
SAM = 'Samwise "Sam" Gamgee'
MERRY = 'Meriadoc "Merry" Brandybuck'
PIPPIN = 'Peregrin "Pippin" Took'
GANDALF = 'Gandalf the Grey'
ARAGORN = 'Aragorn (Strider)'
LEGOLAS = 'Legolas'
GIMLI = 'Gimli'
BOROMIR = 'Boromir'
print 'Gandalf the Grey' in TheFellowshipOfTheRing
# True
print 'Saruman' in TheFellowshipOfTheRing
# False
I'm wondering if implementing container-specific functions, such as __contains__, on a metaclass is a dangerous thing to do, and if so, why?