構(gòu)造方法__init__
構(gòu)造方法也是魔術(shù)方法的一種,此方法我在python對(duì)象與類中已經(jīng)展示過了
注意:在方法中引用類成員變量一定要記得使用self關(guān)鍵字引用
對(duì)象轉(zhuǎn)字符__str__
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
# 返回類轉(zhuǎn)化的字符串
def __str__(self):
return f"name:{self.name},age:{self.age}"
stu2 = Student("jaky", 22)
stu1 = Student("wenwen", 20)
print(str(stu1))
如果不使用該方法打印,那打印出來的只會(huì)是對(duì)象的地址文章來源:http://www.zghlxwxcb.cn/news/detail-481973.html
對(duì)象自定義大小比較
First__lt__
def __lt__(self, other):
return self.age < other.age
Second__le__
def __le__(self, other):
return self.age <= other.age
Third__eq__
def __eq__(self, other):
return self.age == other.age
只需如此就可以打印判斷真假
print(stu2 < stu1)
print(stu1<=stu2)
print(stu2==stu1)
效果文章來源地址http://www.zghlxwxcb.cn/news/detail-481973.html
到了這里,關(guān)于python類中常用的魔術(shù)方法的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!