资讯动态

24:Python-面向对象基础

发布时间:2026/10/8 18:28:17 来源:尧图企业网站定制
一、类与对象1、类描述的是一组具有相同属性和方法的模板。2、对象是类的实例是基于类创建出来的一个类可以创建多个对象。二、类的定义1、类的命名规范遵循大驼峰命名法每个单词的首字母都是大写单词之间没有分隔符如UserInfo2、__dict__是python中用户自定义类实例的一个特殊属性用于以字典形式存储对象的属性3、语法结构class 类名 def __init__(self, 参数列表): self.属性名 参数值 #创建对象 对象名类名参数列表4、示例class Student: def __init__(self, name, age): self.name name self.age age s1Student(张三,23) print(s1.__dict__) #__init_:初始化方法对象创建后自动调用主要用于设置对象的初始状态 #self:方法中的第一个参数表示当前创建的示例对象三、实例方法1、在类中定义实例方法时定义语法与之前学习的函数定义方式是一致的。2、语法结构class 类名: def __init__(self,形参列表) self.属性名参数值 def 方法名(self,形参列表) ... #创建对象 对象名类名(参数列表) 对象名.方法名(实参)3、示例class Car: def __init__(self, c_color, c_brand, c_name,c_price): self.color c_color self.brand c_brand self.name c_name self.price c_price print(Car类型的对象初始化完毕,对象属性已经添加完毕) #定义实例方法 def runing(self): print(f{self.brand}{self.name}正在告诉行驶) def total_cost(self,discount,rate): :param discount: 折扣 :param rate: 税率 :return: 提车总费用 total_cost discount * self.pricerate*self.price return total_cost c1Car(红色,宝马,X7,800000) print(c1.__dict__) c1.runing() print(f提车总费用{c1.total_cost(discount2,rate3)})四、魔法方法1、魔法方法是python中提供的以双下划线开头和结尾的特殊方法用于定义类的特殊行为如:__init__。2、常见方法_ _init_ _初始化方法_ _str_ _字符串表示方法_ _eq_ _比较两个对象是否相等(equal)_ _lt_ _比较两个对象的大小小于less than_ _le_ _比较两个对象的大小小于等于less than or equal_ _gt_ _比较两个对象的大小大于greater than_ _ge_ _比较两个对象的大小大于等于greater than or equal3、示例class Car: def __init__(self, c_color, c_brand, c_name,c_price): self.color c_color self.brand c_brand self.name c_name self.price c_price print(Car类型的对象初始化完毕,对象属性已经添加完毕) #定义实例方法 def runing(self): print(f{self.brand}{self.name}正在告诉行驶) def total_cost(self,discount,rate): :param discount: 折扣 :param rate: 税率 :return: 提车总费用 total_cost discount * self.pricerate*self.price return total_cost #魔法方法 def __str__(self): return f{self.name},{self.color},{self.brand},{self.price} def __eq__(self,other): return self.colorother.color and self.brandother.brand and self.priceother.price and self.nameother.name def __lt__(self,other): return self.priceother.price c1Car(红色,宝马,X7,800000) c2Car(红色,宝马,X7,500000) print(c1) print(c2) print(c1c2) print(c1c2)五、实例属性与类属性1、实例属性实例属性属于每个具体对象的属性每个对象都是独立的。2、类属性类属性是属于类本身的属性所有实例共享的。通过实例查找属性时会先查找实例属性实例属性不存在时再查找类属性。

读完文章,也想定制专属网站?

尧图设计师 24 小时内与您沟通定制方案

免费获取报价 →
↑