class、属性、伪类示例
时间: 2023-09-25 15:10:34 浏览: 45
1. Class示例:
下面是一个Python中的类示例:
```python
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def get_make(self):
return self.make
def get_model(self):
return self.model
def get_year(self):
return self.year
car1 = Car("Toyota", "Camry", 2019)
print(car1.get_make()) # 输出结果:Toyota
```
在上面的示例中,`Car` 是一个类,它有三个属性:`make`、`model` 和 `year`。它也有三个方法:`get_make()`、`get_model()` 和 `get_year()`。通过实例化 `Car` 类,我们可以创建一个名为 `car1` 的对象,并使用 `get_make()` 方法获取 `car1` 的 `make` 属性的值。
2. 属性示例:
下面是一个Python中的属性示例:
```python
class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width
@property
def area(self):
return self.length * self.width
@property
def perimeter(self):
return 2 * (self.length + self.width)
@property
def diagonal(self):
return (self.length ** 2 + self.width ** 2) ** 0.5
rect = Rectangle(5, 3)
print(rect.area) # 输出结果:15
```
在上面的示例中,`Rectangle` 是一个类,它有两个属性:`length` 和 `width`。它也有三个属性方法:`area`、`perimeter` 和 `diagonal`。这些属性方法被装饰为 `@property`,这意味着它们可以像属性一样调用,而不是像方法一样调用。通过实例化 `Rectangle` 类,我们可以创建一个名为 `rect` 的对象,并使用 `area` 属性获取 `rect` 的面积。
3. 伪类示例:
下面是一个CSS中的伪类示例:
```css
a:hover {
color: red;
text-decoration: underline;
}
```
在上面的示例中,`a:hover` 是一个伪类,它表示当鼠标悬停在 `a` 标签上时,应用下划线样式和红色文本颜色。这个伪类只在特定的状态下应用样式,而不是在文档结构上应用样式。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)