news 2026/4/24 4:07:09

Python 之类别

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
Python 之类别

什么是方法和属性,它们是如何工作的?

在这里,我们将深入探讨属性和方法。

我们先仔细看看属性,然后是方法。

属性是属于对象的变量,所以它们保存数据。属性分为两种类型:实例属性和类属性。

实例属性是每个从类创建的对象独一无二的,通常你用方法来设置属性。而类属性则属于该类本身,并且该类的所有实例共享。__init__

访问属性时,使用点符号。

以下是实例属性和类属性的示例,以及如何从对象访问它们:

class Dog: species = "French Bulldog" # Class attribute def __init__(self, name): self.name = name # Instance attribute print(Dog.species) # French Bulldog dog1 = Dog("Jack") print(dog1.name) # Jack print(dog1.species) # French Bulldog dog2 = Dog("Tom") print(dog2.name) # Tom print(dog2.species) # French Bulldog

注意你可以直接从类本身访问类属性,但你需要先创建一个对象并传递数据,才能访问实例属性。

汽车也是很好的例子,因为所有汽车都有型号和颜色:

class Car: def __init__(self, color, model): self.color = color self.model = model car_1 = Car("red", "Toyota Corolla") car_2 = Car("green", "Lamborghini Revuelto") print(car_1.model) # Toyota Corolla print(car_2.model) # Lamborghini Revuelto print(car_1.color) # red print(car_2.color) # green

方法是定义在类内的函数。通过它们,任何由类定义的对象都可以执行操作或修改自身数据的动作。你还可以使用点符号法。

比如,狗会叫。这样我们可以在课堂上设置一个方法,就像你之前的课程中看到的那样:barkDog

class Dog: species = "French Bulldog" def __init__(self, name): self.name = name def bark(self): return f"{self.name} says woof woof!" jack = Dog("Jack") jill = Dog("Jill") print(jack.bark()) # Jack says woof woof! print(jill.bark()) # Jill says woof woof!

类还可以有一种方法:Cardescribe

class Car: def __init__(self, color, model): self.color = color # Instance attribute self.model = model # Instance attribute def describe(self): return f"This car is a {self.color} {self.model}" car_1 = Car("red", "Toyota Corolla") car_2 = Car("green", "Lamborghini Revuelto") print(car_1.describe()) # This car is a red Toyota Corolla print(car_2.describe()) # This car is a green Lamborghini Revuelto
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/4/24 4:01:53

Mate Engine未来路线图展望:即将到来的新功能

Mate Engine未来路线图展望:即将到来的新功能 【免费下载链接】Mate-Engine A free Desktop Mate alternative with a lightweight interface and custom VRM support, though with more features. 项目地址: https://gitcode.com/gh_mirrors/ma/Mate-Engine …

作者头像 李华
网站建设 2026/4/24 3:59:45

超简单llama2.c量化优化:参数迭代调优实战指南

超简单llama2.c量化优化:参数迭代调优实战指南 【免费下载链接】llama2.c Inference Llama 2 in one file of pure C 项目地址: https://gitcode.com/GitHub_Trending/ll/llama2.c llama2.c是一个轻量级的Llama 2推理框架,用纯C语言实现&#xff…

作者头像 李华
网站建设 2026/4/24 3:56:50

分层贝叶斯模型在客户流失预测中的应用与实践

1. 分层贝叶斯模型的核心思想与应用场景 分层贝叶斯模型(Hierarchical Bayesian Model)是一种强大的统计建模框架,特别适合处理具有层次结构的数据。在客户流失预测场景中,这种层次性表现为:同一行业内的不同企业( SMEs )共享某些共性特征&am…

作者头像 李华