My work-out: This is an assignment
class Person(object):
def __init__(self, name):
self.name = name
def __str__(self):
if isinstance(person1, Lecturer):
return "Name: " + self.name + "\tOccupation: " + self.occupation
elif isinstance(person2, Student):
return "Name: " + self.name + "\tStudent Number: " + self.studentNumber
class Lecturer(Person):
def Occupation(self, occupation):
self.occupation = occupation
class Student(Person):
def StudentNumber(self, studentNumber):
self.studentNumber = studentNumber
person1 = Lecturer("Elisha Nsemwa")
person2 = Student("Fabian Hamza")
person1.Occupation("Senior Lecturer")
person2.StudentNumber("HD5603")
print person1
print person2
My output:
Name: Elisha Nsemwa Occupation: Senior Lecturer
"assignment.py", line 26, in <module>
print person2
"assignment.py", line 7, in __str__
return "Name: " + self.name + "\tOccupation: " + self.occupation
AttributeError: 'Student' object has no attribute 'occupation'
person1 execute the if part, this is OK the output get printed, now my error is person2 execute the if not the elif; how can I correct this
In
def __str__(self):
if isinstance(person1, Lecturer):
return "Name: " + self.name + "\tOccupation: " + self.occupation
elif isinstance(person2, Student):
return "Name: " + self.name + "\tStudent Number: " + self.studentNumber
you are testing person1 and person2, so isinstance(person1, Lecturer) is always true. What you want to know is the instance of self:
... def __str__(self):
... if isinstance(self, Lecturer):
... return "Name: " + self.name + "\tOccupation: " + self.occupation
... elif isinstance(self,Student):
... return "Name: " + self.name + "\tStudent Number: " + self.studentNumber
...
...
>>> print person1
Name: Elisha Nsemwa Occupation: Senior Lecturer
>>> print person2
Name: Fabian Hamza Student Number: HD5603
Related
I need to find a way how to append a person (form inputs I got) to a list. I always get:<main.List object at 0x0000027FD63B6B60>
class Person:
def __init__(self, name, surname, age, phone_number):
self.name = name
self.surname = surname
self.age = age
self.phone_number = phone_number
def __str__(self):
return f"\n{self.name} " + f"\t" + f"{self.surname} " + f"\t" + f"{self.age} " + f"\t" + f"{self.phone_number} "
class Input:
def __init__(self):
pass
def input_data(self):
self.name = input("\nInsert a name: \n")
self.surname = input("Insert a surname: \n")
self.age = int(input("Insert an age: \n"))
self.phone_number = input("Insert a phone number: \n")
person = NewPerson(self.name, self.surname, self.age, self.phone_number)
return person
class List:
def __init__(self):
pass
def data_to_list(self, name, surname, age, phone_number):
self.name = name
self.surnam = surnam
self.age = age
self.phone_number = phone_number
list= []
list = list.extend(self.name, self.surname, self.age, self.phone_number)
return list
First, don't use variable names named after Python's built-ins (list), use lst for example.
Also, list.extend always returns None so there's no point to assign the return value to a variable.
In constructor of class List assign to self an empty list and in method data_to_list() use list.append to put newly crated Person() to a list.
For example:
class Person:
def __init__(self, name, surname, age, phone_number):
self.name = name
self.surname = surname
self.age = age
self.phone_number = phone_number
def __repr__(self):
return f"Person({self.name}, {self.surname}, {self.age}, {self.phone_number})"
class List:
def __init__(self):
self.lst = []
def data_to_list(self, name, surname, age, phone_number):
self.name = name
self.surname = surname
self.age = age
self.phone_number = phone_number
self.lst.append(
Person(self.name, self.surname, self.age, self.phone_number)
)
l = List()
l.data_to_list("John", "Smith", "33", "+123456")
l.data_to_list("Alice", "Green", "32", "+654321")
print(l.lst)
Prints:
[Person(John, Smith, 33, +123456), Person(Alice, Green, 32, +654321)]
I have this situation: When a modelf field is filled, it must not be greater than other modelĀ“s field. I wrote this validator.
class Insumo(models.Model):
nombre = models.CharField(max_length=100)
cantidadexistencias = models.DecimalField(max_digits=50, decimal_places=3, validators=[MinValueValidator(0)])
def __str__(self):
return self.nombre + " "+str(self.cantidadexistencias)
class InsumoProduction(models.Model):
idproduction = models.ForeignKey('Production', on_delete=models.CASCADE)
idinsumo = models.ForeignKey('Insumo', on_delete=models.CASCADE)
#Validar que la cantidad usada sea maximo el numero de existencias
cantidadusada = models.DecimalField(max_digits=50, decimal_places=3,validators=[insumo_existencias])
def save(self,*args,**kwargs):
insumo = Insumo.objects.get(id = self.idinsumo_id)
insumo.cantidadexistencias -= self.cantidadusada
insumo.save()
super(InsumoProduction,self).save(*args,**kwargs)
class Meta:
constraints = [
models.UniqueConstraint(fields=["idproduction", "idinsumo"],
name='unique_insumoproduction')
]
def __str__(self):
return self.idproduction.idfinalproduct.idproduct.nombre +" "+ self.idproduction.idfinalproduct.idtaste.nombre \
+ " "+ self.idinsumo.nombre + " "+ str(self.cantidadusada) + " Fecha Produccion " + str(
self.idproduction.fechaproduccion)
Those are my models, and my validator is here:
from django.core.exceptions import ValidationError
from ubindustries.ubapi.models import models
from django.utils.translation import gettext_lazy as _
def insumo_existencias(value):
insumo = models.Insumo.objects.get(id=models.InsumoProduction.idinsumo_id)
if (insumo.cantidadexistencias < value):
raise ValidationError(
_('Error no hay existencias suficientes'),
)
I got this error message:TypeError at /ubapi/insumoproduction/add/
int() argument must be a string, a bytes-like object or a number, not 'DeferredAttribute
Consider the following model :
from django.db import models
class Album(models.Model):
id = models.IntegerField(primary_key=True,null=False)
artist = models.CharField(max_length=200)
album_title = models.CharField(max_length = 250)
genre = models.CharField(max_length=100)
album_logo = models.CharField(max_length = 200)
def __str__(self):
return "id = " + str(self.id) + " artist = " + self.artist + " album = " + self.album_title + " genre = " + self.genre
class Song(models.Model):
id = models.IntegerField(primary_key=True)
album = models.ForeignKey(Album,on_delete=models.CASCADE)
file_type = models.CharField(max_length = 200)
song_title = models.CharField(max_length = 200)
def __str__(self):
return "id = " + str(self.id) + "album = " + self.album.album_title + "song = " + self.song_title
When i am inserting a row in either Album or Song using positional parameters and not giving, django is providing NULL to that particular row. Why so?
First of all, there is no need of explicitly declaring a field named 'id' as Django already creates an id field with every model by default and auto-increments it.
In any case, if you want to deliberately declare a primary key it is recommended do it in the following manner:
id = models.AutoField(primary_key=True)
This is an auto-incrementing primary key.
Reference Official Django Docs:
https://docs.djangoproject.com/en/1.11/topics/db/models/#automatic-primary-key-fields
When Iam trying to get the degree of a student and do the return value with that code:
def __str__(self):
return self.student_subject + " " + Student.last_name
I got the above error message.
Here is the whole Django code:
from django.db import models
# Create your models here.
class Student(models.Model):
first_name = models.CharField(max_length=15)
last_name = models.CharField(max_length=15)
age = models.IntegerField(default=0)
birth_date = models.DateTimeField()
def __str__(self):
return self.first_name + " " + self.last_name
class Degree(models.Model):
student_id = models.ForeignKey(Student, on_delete=models.CASCADE)
student_subject = models.CharField(max_length=150)
student_degree = models.IntegerField(default=0)
def __str__(self):
return self.student_subject + " " + Student.last_name
the error is happening because I trying to inherite the return from the above class Student
And here is the error message:
TypeError at /admin/sellingportal/degree/
Can't convert 'DeferredAttribute' object to str implicitly
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/sellingportal/degree/
Django Version: 1.10.1
Exception Type: TypeError
Exception Value:
Can't convert 'DeferredAttribute' object to str implicitly
Exception Location: C:\Users\Muham\PycharmProjects\managementsite\managementstudio\sellingportal\models.py in __str__, line 22
Python Executable: C:\Python34\python.exe
Python Version: 3.4.4
Python Path:
['C:\\Users\\Muham\\PycharmProjects\\managementsite\\managementstudio',
'C:\\Windows\\SYSTEM32\\python34.zip',
'C:\\Python34\\DLLs',
'C:\\Python34\\lib',
'C:\\Python34',
'C:\\Python34\\lib\\site-packages']
Server time: Fri, 16 Sep 2016 01:04:08 +0200
Just change it to:
def __str__(self):
return self.student_subject + " " + self.student_id.last_name
and all should be fine.
You cannot set Student.last_name because you have to show from which object, should the last name be taken from.
#C:/Python32
class Person:
def __init__(self, name = "joe" , age= 20 , salary=0):
self.name = name
self.age = age
self.salary = salary
def __printData__(self):
return " My name is {0}, my age is {1} , and my salary is {2}.".format(self.name, self.age, self.salary)
print(Person)
class Employee(Person):
def __init__(self, name, age , salary ):
Person. __init__ (self,name = "Mohamed" , age = 20 , salary = 100000)
def __printData__(self):
return " My name is {0}, my age is {1} , and my salary is {2}.".format(sef.name, self.age, self.salary)
print(Employee)
You need to indent the second line here, from:
def __printData__(self):
return " My name is {0}, my age is {1} , and my salary is {2}.".format(sef.name, self.age, self.salary)
to:
def __printData__(self):
return " My name is {0}, my age is {1} , and my salary is {2}.".format(sef.name, self.age, self.salary)
You need to indent the second to last line because it is after a function definition. Also, at one point you use sef instead of self. I've corrected both of these below:
class Person:
def __init__(self, name = "joe" , age= 20 , salary=0):
self.name = name
self.age = age
self.salary = salary
def __printData__(self):
return " My name is {0}, my age is {1} , and my salary is {2}.".format(self.name, self.age, self.salary)
print(Person)
class Employee(Person):
def __init__(self, name, age , salary ):
Person. __init__ (self,name = "Mohamed" , age = 20 , salary = 100000)
def __printData__(self): # The problem was the line after this one.
return " My name is {0}, my age is {1} , and my salary is {2}.".format(self.name, self.age, self.salary)
print(Employee)