7.10. python的根类¶
python的所有类都直接或间接继承object类,它是所有类的“祖先”。 object有很多方法,主要学习两个方法
__str__():返回该对象的字符串表示
__eq__(other):指示其他某个对象是否与此对象“相等”
7.10.1. __str__()¶
#!/usr/bin/env python
# -*- coding:utf8 -*-
# auther; 18793
# Date:2019/5/18 8:10
# filename: str方法.py
class Person(object):
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
template = "Person [name={0},age={1}]"
s = template.format(self.name, self.age)
return s
person = Person("hujianli", 18)
print(person)
7.10.2. __eq__()¶
#!/usr/bin/env python
#-*- coding:utf8 -*-
# auther; 18793
# Date:2019/5/18 8:14
# filename: eq方法.py
class Person(object):
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
template = "Person [name={0},age={1}]"
s = template.format(self.name, self.age)
return s
def __eq__(self, other):
if self.age == other.age and self.name == other.name:
return True
else:
return False
person1 = Person("hujianli", 18)
person2 = Person("hujianli", 18)
print(person1 == person2)