python类中常用的内置方法

105 阅读1分钟
class people:

    def __init__(self, name, age, hobby):
        self.name = name
        self.age = age
        self.hobby = hobby

    def __str__(self):
        return f"你好,我叫{self.name},今年{self.age}岁了,我的爱好是:{self.hobby}"

    def __lt__(self, other):
        return self.age < other.age

    def __le__(self, other):
        return self.age <= other.age

    def __eq__(self, other):
        return self.age == other.age
  1. 内置__init__方法,上一章有讲,对象的参数会依次传给构造方法,然后依次给成员变量赋值,在创建类对象(构造类) 的时候,会自动执行,在创建类对象(构造类) 的时候,将传入的参数自动传递给__init__方法使用。

  2. 内置__str__方法,可以通过__str__ 转换为字符串的行为,使用__str__,可以指定在用print对象或者使用str()打印对象的话,返回指定的内容。

# cxk = people("鸡哥", 18, "打篮球")
# print(cxk)      # <__main__.people object at 0x000001E22B037C90>
# print(str(cxk)) # <__main__.people object at 0x000002413F0A7C90>
#
# print(cxk)      # 你好,我叫鸡哥,今年18岁了,我的爱好是:打篮球
# print(str(cxk)) # 你好,我叫鸡哥,今年18岁了,我的爱好是:打篮球
  1. 内置__lt__方法,、如果没有定义这个方法,直接比较两个对象是会报错的 TypeError: '<' not supported between instances of 'people' and 'people',如果定义了则会按照定义好的属性去比较。
cxk = people("鸡哥", 18, "打篮球")
hero = people("王拿铁", 18, "敲代码")
print(cxk > hero)   # TypeError: '>' not supported between instances of 'people' and 'people'
print(cxk > hero)   # False
print(cxk < hero)   # True
  1. 内置__le__方法,可以定义>=,<=两种比较符运算,而__lt__只能定义<、>。
print(cxk >= hero)   # False
print(cxk <= hero)   # True
  1. 内置__eq__方法,用来定义==比较的,如果不定义__er__是默认存在的,默认比较的是内存地址。
print(cxk == hero)   # false