I get expected indentation block at line - python-2.7

#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)

Related

How do I add a variable/variables to a list

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)]

Django Datetime function

Am aiming for the value 'grade' to be incremented by 1 on 25th every month. The below function doesn't seem to be working. Where could I be going wrong?
Attached is the model and function.
class Student(models.Model):
student_name = models.CharField(max_length=100, null=True)
extra_role = models.CharField(max_length=100, default='None', null=True)
gender = models.CharField(max_length=20, choices = gender, default = "female")
dob = models.DateField(null=True, blank=True)
grade = models.IntegerField(choices=grade)
parent_phone = PhoneField(blank=True, help_text='Contact phone number')
# admNo = models.AutoField()
#property
def age(self):
if(self.dob != None):
age = date.today().year - self.dob.year
return age
#property
def sgrade(self):
if datetime.today().day == 25:
grade = self.grade +1
return grade
Please try this one :
def age(self):
if(self.dob != None):
today = datetime.datetime.today()
return today.year - self.dob.year - ((today.month, today.day) < (self.dob.month, self.dob.day))
def sgrade(self):
if datetime.datetime.now().day == 25:
grade = self.grade +1
return grade
Don't forget to import datetime

Django - Select only specific rows from a query

I've started to learn django and as my first project I am trying to create a catalog.
I created 3 tables
Students
Catalog
Link table between those 2
This is how my models.py looks like:
class Catalog(models.Model):
Class = models.CharField(max_length =30)
def __str__(self):
return str(self.Class)
class StudentiAn4(models.Model):
Username = models.ForeignKey(User)
FirstName = models.CharField(max_length=50)
LastName = models.CharField(max_length=50)
Group = models.CharField(max_length=4)
def __str__(self):
return str(self.Username) + ' ' + self.FirstName +' ' + self.LastName
class CatalogStudenti(models.Model):
catalog = models.ForeignKey(Catalog)
student = models.ForeignKey(StudentiAn4)
grade = models.IntegerField()
def __str__(self):
return str(self.catalog) +' ' + str(self.student)
In views :
def studenti(request):
query = CatalogStudenti.objects.all()
return render(request, 'users/Studenti.html',{'query': query})
As a logged in user(Username: 123, FirstName: test1, LastName: test1_LN), I would like to see only grades assigned to me, not all grades.
Can you please tell me how can I filter the output so that I see only the grades assigned to me?
Current output:
123 test1 test1_LN - SEP 5
234 test2 test2_LN - ASC 4
123 test1 test1_LN - AACEP 6
Desired Output:
123 test1 test1_LN - SEP 5
123 test1 test1_LN - AACEP 6
Change the queryset in the view funtion to filter by the user field from student:
query = CatalogStudenti.objects.filter('student__Username'=request.user)

Python class __str__

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

How to edit an object of Super Class via an object in the SubClass

basically i have two class (Customer, EmpClass), and i tried many times to find a way in witch one employee (object of EmpClass) can perform the functionalities that are available to the Customer Class's object,ex Deposit,withdraw and so on and off course on behalf of one customer, and later on time of enquiry i can tell which employee have perform what operations for a particular customer and like that .
and thanks in advance :)
my models :
class Customer(object):
''' this class contains all Customer related Information and Functions'''
BankName = "SBH"
def __init__(self, Cname,CacountNumber, Cbalance):
self.Cname = Cname
self.CacountNumber = CacountNumber
self.Cbalance = Cbalance
def Deposit(self, DepositAmount):
self.Cbalance = self.Cbalance + DeposetAmount
def WithDraw(self, WithDrawAmount):
if WithDrawAmount > self.Cbalance:
raise InSuffetiantFunds
self.Cbalance = self.Cbalance - WithDrawAmount
def C_Info(self):
print "Bank Name :", Customer.BankName
print "Customer Name :", self.Cname
print "Customer Acount Number : ", self.CacountNumber
print "Customer Balance :", self.Cbalance
class EmpClass(Customer):
''' this class contains all Employee related Information and Functions'''
BankName = "SBH"
def __init__(self, EmpName,EmpId,):
self.EmpName = EmpName
self.EmpId = EmpId
Customer.__init__(self, Cname,CacountNumber, Cbalance)
def E_Info(self):
print "Bank Name :", EmpClass.BankName
print "Employee Name:", self.EmpName
print "Employee Id : ", self.EmpId
In python there is super which enables you to call the inherited classes functionalities.
class EmpClass(Customer):
def __init__(self, EmpName, EmpId, *args, **kwargs):
self.EmpName = EmpName
self.EmpId = EmpId
super(EmpClass, self).__init__(*args, **kwargs)
If you are on python3 you no longer need to pass arguments to super()
Use *args and **kwargs to pass arguments to the parent, without defining them again in the subclass.