Everything in Python is an object. Objects have types(belong to classes). Objects also have methods(a set of procedures for interacting with them).
Defying Classes
# 实例
from datetime import date
class Person(object):
# 自定义一个类 Person; 括号内'object'可以省去
def __init__(self, f_name, l_name):
# __init__() 是类的初始化方法;它在类的实例化操作后 会自动调用,不需要手动调用
'Create a person using first and last names'
self.first_name = f_name
self.last_name = l_name
self.birthdate = None
def get_name(self):
# 添加一个方法 get_name,哪个对象调用了这个方法,self就是那个对象
return self.first_name + ' ' + self.last_name
def get_age(self):
return date.today().year - self.birthdate.year
def set_birthdate(self, dob):
# Assume dob is of type date.
# Arguement里面的 self 在执行set_birthdate方法时作为不直接参与语句的参数,帮助程序确定执行对象,即下面 的p1,
#不需要在执行该方法时赋值,即只输入p1.set_birthdate(date(1997, 7 , 12))
self.birthdate = dob
def __str__(self):
# 定义一个字符串(追踪对象属性信息变化),在执行 print(object)的命令时输出
return self.first_name + ' ' + self.last_name
p1 = Person('Malala', 'Yousafzai')
p1.set_birthdate(date(1997, 7 , 12))
print(p1, p1.get_age())
>>> Malala Yousafzai 22
Subclasses and Inheritance
- Inheritance
Allows to build hierarchies of related abstractions
Subclass inherit data attributes and methods from their superclass(classes that are higher in the hierarchy)
On top of the hierarchy in class object
Subclasses can:
Add new data attributes and methods
Override data attributes and methods of the superclass
# 实例
class LSEPerson(Person):
# This is a class variable
next_id_num = 1 # unique identification number
def __init__(self, f_name, l_name):
'Create an LSE person using first name and last name'
Person.__init__(self, f_name, l_name)
self.id_num = LSEPerson.next_id_num
LSEPerson.next_id_num += 1
def get_id_num(self):
'''Gets self\'s unique LSE number'''
return self.id_num
def __lt__(self, other):
'''Returns True if self\'s id number is smaller than other\'s id number'''
return self.id_num < other.id_num
staff1 = LSEPerson('Milena', 'Tsvetkova')
print(staff1, staff1.get_id_num())
staff2 = LSEPerson('Ken', 'Benoit')
print(staff2, staff2.get_id_num())
print(staff1 < staff2)
print(p1 < staff1)#compare the name
print(staff1 < p1)#compare teh id number
- Special Methods
_int_() - called when a class is initiated
_str_() - called by print() and str()
_lt_() - overloads the < operator
_le_() - overloads the <= operator
_eq_() - overloads the == operator
_ne_() - overloads the != operator(defaults to opposite of _eq_())
_gt_() - overloads the > operator
_ge_() - overloads the >= operator