Accessing parent class method error - python-2.7

I am trying to learn super implementation in Python and I have tried various help threads on SO but I am not able to implement the following code:
class Person:
def __init__(self, first, last, age):
self.firstname = first
self.lastname = last
self.age = age
def __str__(self):
return self.firstname + " " + self.lastname + ", " + str(self.age)
class Employee(Person):
def __init__(self, first, last, age, staffnum):
super(Employee, self).__init__(first, last, age)
self.staffnumber = staffnum
def __str__(self):
return super(Employee, self).__str__() + ", " + self.staffnumber
x = Person("Marge", "Simpson", 36)
y = Employee("Homer", "Simpson", 28, "1007")
print(x)
print(y)
What is wrong with this syntax in above code?
return super(Employee, self).__str__() + ", " + self.staffnumber

In Python 2.7 there are leftovers of the old hierarchy. Not all classes inherit from object, which is the default in Python 3. If you do not explicitly inherit object Python will use old style objects, which fail with Super which depends on this.
All you need to do is explicitly make sure all your objects eventually inherit object:
class Person(object):
In Python 3 this is 'fixed'.
An alternative is to forego super in favor of using the methods as class methods, which will work with both types of objects:
Person.__init__(self,first,last,age)
Person.__str__(self)

Related

How to convert a models.IntegerField() instance to int?

I am working on Django 4.0.2 in python 3.10.2
I've read How to convert a models.IntegerField() to an integer(the poster actually need copy-constructor function).And I've searched for Google.
But it doesn't help.
what I want to do is:
#In app/models.py
class Foo:
a1 = models.IntergeField()
a2 = models.IntergeField()
#....
#many else
b1 = convertToInt(a1) * 3 + convertToInt(a2) *4 + convertToInt(a7) #calc by needing
b2 = convertToInt(a2) * 2 + convertToInt(a3) + convertToInt(a5) #calc by needing
#....
#many else
#b(b is price actually) will be used in somewhere else.Its type need be int for programmer-friendly using
any advice?
P.S. English is not my first language.Please forgive my syntax mistakes.
Edit 1:
if just a1 * 3, I will receive
TypeError: unsupported operand type(s) for *: 'IntegerField' and 'int'
And I'd like to explain why the solution in the above attached link is not work
the first answer use:
class Foo(models):
nombre_etudiant = models.IntergeField()
place_disponible =models.IntegerField(blank=True,null=True)
def __init__(self,*args,**kwargs):
super(Foo, self).__init__(*args, **kwargs)
if self.place_disponible is None:
self.place_disponible = self.nombre_etudiant
which I still can't mutiply the num by n. The code just do copying.I still can't get the value in int type.
the 2nd solution
class MyModel(models):
nombre_etudiant = models.IntergeField()
place_disponible =models.IntegerField()
def save(self, *args, **kwargs):
if not self.place_disponible:
self.place_disponible = int(nombre_etudiant)
super(Subject, self).save(*args, **kwargs)
self.place_disponible = int(nombre_etudiant) this will catch excepetion like TypeError: int() argument must be a string, a bytes-like object or a real number, not 'IntegerField'
Since you indicated in the comments that you don't need to store the derived attributes, I propose the following solution. Here the attributes are calculated every time and you can use them as you would use a1 and a2 attributes.
class Foo(models.Model):
a1 = models.IntegerField()
a2 = models.IntegerField()
#property
def b1(self):
return self.a1*3 + self.a2*4 # + ...
#property
def b2(self):
return self.a2*3 + self.a3 # + ...

Name error when trying to print an object of a class

I'm new to python and need some help. My code is below. I'm trying to get the formatted table from a list of user details inputted but keep getting error stating 'NameError: name 'games' is not defined' Not sure what I am doing wrong to get it to print, please help.
class game():
def _init_(self,name,platform,genre,no_of_players,online_functionality):
self.name = name
self.platform = platform
self.genre = genre
self.no_of_players = no_of_players
self.online_functionality = online_functionality
def __repr__(self):
print()
print("%-15s%-15s%-15s%-15s%-15s" % ("name" , "platform" ," genre" ,"no_of_players","online_functionality"))
print("---------------------------------------------------------------------------------")
print("%-10s%-10s%-10s%-10s%-10s%" %(games.name,games.platform,games.genre,games.no_of_players,games.online_functionality))
print()
def __str__(self):
print()
print("%-15s%-15s%-15s%-15s%-15s" % ("name" , "platform" ," genre" ,"no_of_players","online_functionality"))
print("------------------------------------------------------------------------")
print("%-10s%-10s%-10s%-10s%-10s%" %(games.name,games.platform,games.genre,games.no_of_players,games.online_functionality))#formats and aligns columns
print()
def get_game_from_user():
gameList =[]
games = game()
games.name= input("Enter name of game: ")
games.platform= input("Enter Platform (e.g. XBox, PlayStation, PC etc: ")
games.genre = input("Genre (e.g. Sport, Shooter, Simulation etc.): ")
games.no_of_players= int(input("Enter number of players: "))
games.online_functionality= input("Enter if it has online functionality or not : ")
gameList.append(games)
print(gameList)
First Problem:
Use self inside your class to access to your object not games. change these:
games.name, games.platform , games.genre, ...
and other stuffs like them to these:
self.name, self.platform , self.genre, ...
Second problem:
in your code is that you must return what you want inside the __str__ and __repr__ not print them:
def __repr__(self):
result = ""
result += "%-15s%-15s%-15s%-15s%-15s" % ("name" , "platform" ," genre" ,"no_of_players","online_functionality\n")
result += "---------------------------------------------------------------------------------\n"
result += "%-10s%-10s%-10s%-10s%-10s" %(self.name,self.platform,self.genre,self.no_of_players,self.online_functionality)
result += "\n"
return result
source: python data model

How to get currently selected choice from CharField in Django?

I'm trying to get the currently selected choice from the CharField and use it in str method like this:
class Foo(models.Model):
measurement_value = models.FloatField(max_length=200)
CHOICES = (('a', 'Alpha'), ('b', 'Beta'))
choice = models.CharField(max_length=5, choices=CHOICES, default='a')
def __str__(self):
"""String representation for the foo object."""
return str(self.measurement_value) + " " + self.choice
So for example, if I'd like to add object foo with measurement 10.5 and choice 'a' (Alpha), str would return this: "10.5 Alpha"
Currently, the code that I provided returns this: "10.5 a".
You can get the human readable choice name by using instance method get_{}_display
your example
def __str__(self):
return str(self.measurement_value) + " " + self.get_choices_display()

Manipulating instances of a class change the whole class

So I'm struggling. I've seen quite a few posts on this topic, but after a couple hours struggling with the problem, I can't figure this out. Here are a few snippets of code I have. I'd like to be able to change one instance of the class without the other being changed as well, and I'm coming up short
class voter:
def __init__(self, iPositon, jPosition, affiliation):
self.affiliation = affiliation
self.iPositon = iPositon
self.jPosition = jPosition
class district:
def __init__(self, *listOfVotersPassed):
# super(district, self).__init__()
self.listOfVoters = []
for x in listOfVotersPassed:
self.listOfVoters.append(x)
class city:
def __init__(self, *listOfDistrictsPassed):
self.listOfDistricts = []
for x in listOfDistrictsPassed:
self.listOfDistricts.append(x)
def main():
# I have a list of class district that I pass to city()
startCity = city(*startCityList)
solutionCity = city(*solutionCityList)
print solutionCity.listOfDistricts[0].listOfVoters[0].affiliation # Democrat
print startCity.listOfDistricts[0].listOfVoters[0].affiliation # Democrat
solutionCity.listOfDistricts[0].listOfVoters[0].affiliation = "Republican"
print solutionCity.listOfDistricts[0].listOfVoters[0].affiliation # Republican
print startCity.listOfDistricts[0].listOfVoters[0].affiliation # Republican
if __name__ == "__main__":
main()
edit.
So I was asked about how I created the instance(s) of city. I have a file I'm reading in, each has either R or D in each line.
file = open(fileName)
# import contents
startVoterList = []
solutionVoterList = []
for line in file:
for house in line:
if " " in house:
pass
elif "\n" in house:
pass
else:
startVoterList.append(house)
solutionVoterList.append(house)
I also updated the classes, now each is in the following format. No changes besides the "(object)" after each class className.
class voter(object):
def __init__(self, iPositon, jPosition, affiliation):
self.affiliation = affiliation
self.iPositon = iPositon
self.jPosition = jPosition

How do I fix the part in __str__ so it would display the name of the instance within the class? Python 2X

How do I change the code so that it would return a is a square with side:5 and area:25 ?? when I call print a?
class Square():
def __init__(self, length):
self.length = length
def area(self):
return self.length ** 2
def __str__(self): #this is the part I don't know how to write
return "is a square with side:%s and area:%s." % (self.length, self.area())
a = Square(5)
print a
I guess you want to get the name of the variable that you asign with your class, right??
I don't know how to do that or is that is posible (or usefull in any way) because you can have have multiples variables pointing to the same object
for example in this
a=SomeObject()
b=a
c=a
d=c
and in this case how you will know which one you are using if all of them point to the same object?
A alternative is give your class a extra paremetrer with the name that you wish for you instance
class Square():
def __init__(self, length,name=""):
self.length = length
self.name = name
def area(self):
return self.length ** 2
def __str__(self): #this is the part I don't know how to write
return "%s is a square with side:%s and area:%s." % (self.name, self.length, self.area())
a = Square(5,'MySquare')
print a # MySquare is a square with side:5 and area:25.