Q: Windows/DOS uses Carriage Return and Line Feed ("\r\n") as a line ending, while Unix uses just Line Feed ("\n"). Why this example in Jupyter Notebook shows that the string returned by infile.read() only contains "\n". Is there something wrong?
A: Excellent Question! Let's do an experiment to investigate this phenomenon.A
B
C
Note that you should press ENTER after "C" so that the last line
contains a line ending.
infile = open("test.txt", "r")
s = infile.read()
print(len(s), repr(s))
infile.close()
infile = open("test.txt", "br")
b = infile.read()
print(len(b), repr(b))
infile.close()
Q: What's the meaning of the "self" parameter in a class method? Is it used to specify this is a private member function?
A: The quick answer is "No", but we must clarify this (and related) concept with a couple of examples.#include <iostream>
using std::cin;
using std::cout;
using std::endl;
class Student {
public:
Student(int y) { year = y; }
int getYear() { return year; }
private:
int year;
};
class Teacher {
public:
int calcAge(Student a) {
int age;
// age = 2021 - a.year;
age = 2021 - a.getYear();
return age;
}
};
int main()
{
Student alice(1999);
Student bob(2000);
Teacher ted;
cout << ted.calcAge(alice) << endl;
cout << ted.calcAge(bob) << endl;
return 0;
}
class Student:
def __init__(self, y):
self.year = y
def getYear(self):
return self.year
class Teacher:
def calcAge(self, a):
age = 2021 - a.year
# age = 2021 - a.getYear()
return age
def main():
alice = Student(1999)
bob = Student(2000)
ted = Teacher()
print( ted.calcAge(alice) )
print( ted.calcAge(bob) )
main()
class Student:
def __init__(self, y):
self.year = y
def getYear(self):
return self.year
class Teacher:
def __init__(self, n):
self.age = n
def calcAgeDiff(self, a):
studentAge = 2021 - a.year
return self.age - studentAge
def main():
alice = Student(1999)
ted = Teacher(28)
print( alice.getYear(), Student.getYear(alice) )
print( ted.calcAgeDiff(alice), Teacher.calcAgeDiff(ted, alice) )
main()
class Student:
def __init__(self, y):
self.__year = y
def getYear(self):
return self.__year
def main():
alice = Student(1999)
print( alice.getYear() )
print( alice.__year )
main()