Python Forum
Help on displaying tostring on class.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help on displaying tostring on class.
#1
Hi I have got all the getters and setters for each property of the student class assignment which I have name, id number, date of birth and grade. How can I get the tostring to display it like this:

Name
ID Number
Date of Birth
Grade Level
I have set like this
class Student:
  def __init__(self, x, y, z, a):
    self.__x = x # name
    self.__y = y # ID number
    self.__z = z # Date of birth
    self.__a = a # graduation year
I also put the getters and setters too and I need help. This is what I have so far:
  def toString(self):
    return f'{self.__class__.__name__}({self.__x}, {self.__y})'

name = Student("Javier", 31036, 10/26/2002, 12) 
print(name.get_x())
print(name.get_y())
name.toString()
print(name.toString())
print(name.get_a())
Here's what it prints
Javier
31036
Student(Javier, 31036)
0.00192115577673096135
How can I get it to display like that and will I need to modify the toString?
Reply
#2
Why are you using double underscores attribute names and setters and getters? Not only is it common practice in Python to have class attributes plainly visible, I think it is the preferred approach. Unless an attribute has code associated with setting or getting the attribute I would not use setters and getters.

And why are your attribute names so horrible? __a, __x? What kind of naming convention is that? Student should look something like this:
class Student:
  def __init__(self, name, id_, dob, grad_date):
    self.name = name
    self.id = id_
    self.dob = dob
    self.graduation_date = grad_date

def __repr__(self):
    return f'Student(self.name}, id={self.id}, dob={self.dob}'
Student should define __repr__ or __str__, but I don't think something like to_string belongs in the Student class. You should not force users of the Student class into using your output format. I would write a helper function for my program that knows how to get info from a student object and print formatted output.

def print_student(student):
    print(f'Student : {student.name}')
    ...
ndc85430 and buran like this post
Reply
#3
Also 10/26/2002 as DoB is not what you think it is
>>> 10/26/2002
0.00019211557673096135
Probably you want it to be str (enclosed in quotes) or some sort of date object?

As pointed by @deanhysted - getters and setters are not needed and anti-pythonic in this case.
method toString (or to_string) is unnecessary.

Also check https://dbader.org/blog/meaning-of-under...-in-python
so, if you want to indicate that some attribute is "for-internal-use-only" - you should be using single leading underscore, not double.
ndc85430 likes this post
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#4
Yeah, the reason why we have to use double underscores is mainly that the teacher requires them since he is out on quarantine and the teacher requires the toString method to display it like.

Output:
Name ID Number DOB Graduation date
This is what the teacher told us
Write a student class that has four properties (private variables): date of birth, name, ID number, and grade level. Write getters and setters for each property. Finally, write a toString() method that displays the student in the following format:

Name

ID number

Date of Birth

Grade Level
Reply
#5
A single leading underscore indicates the variable should be thought of as private (there is no real private in Python). A double leading underscore results in python renaming the variable to include the class name (name mangling). This can lead to surprising behaviors if you subclass from a class that has double underscore attributes. This is demonstrated in the class inheritance below:
class Student:
    def __init__(self, first_name, last_name):
        self.__first_name = first_name
        self.__last_name = last_name

    def name(self):
        return f'{self.__first_name} {self.__last_name}'

class GraduateStudent(Student):
    def __init__(self, first_name, last_name, honorific=None):
        super().__init__(first_name, last_name)
        self.__honorific = honorific

    def name(self):
        if self.__honorific is None:
            return super().name()
        return f'{self.__honorific} {self.__first_name} {self.__last_name}'

x = GraduateStudent('Jimmy', 'Dean')
y = GraduateStudent('Jimmy', 'Dean', 'Dr.')
print(x.name())
print(y.name())
Output:
Jimmy Dean Traceback (most recent call last): File "...", line 22, in <module> print(y.name()) File "...", line 17, in name return f'{self.__honorific} {self.__first_name} {self.__last_name}' AttributeError: 'GraduateStudent' object has no attribute '_GraduateStudent__first_name'
Python renames __first_name defined in Student to _Student__first_name. When GraduateStudent tries to use __first_name Python turns this name into _GraduateStudent__first_name. Using __first_name hides the attribute from the subclass.

It may seem odd hiding attributes from a subclass, but there are times when this is necessary and the double underscore naming convention was created to fulfill that need. If your intention is to just mark your variables as private, use the single underscore.

I think you already know how to write toString(). You just need to add some newline characters (\n) to the format string.
Reply
#6
Yeah I do have the old code of the toString from the last assignment I've turned in and its this one that I have here
  def toString(self):
    return f'{self.__class__.__name__}({self.__x}, {self.__y})'
Would I change it to this?
  def toString(self):
    return f'{self.__class__.__name__}({self.__name}, {self.__id} \n {self.__z}, {self.__a})''
I may need to add something to it. Also It has to be in one class in order to meet the requirements.
Reply
#7
Finally solved it!
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020