十个简单的Python类的例子

十个简单的Python类的例子
涵盖了基本的类概念、实例属性、方法及一些高级应用。
内容从浅入深。

例子 1:定义一个简单的类

class Dog:
    def __init__(self, name):
        self.name = name

    def bark(self):
        return "Woof!"

# 使用类
my_dog = Dog("Buddy")
print(my_dog.name)  # 输出: Buddy
print(my_dog.bark())  # 输出: Woof!

例子 2:类属性和实例属性

class Car:
    wheels = 4    # 类属性,所有实例共享

    def __init__(self, color):
        self.color = color  # 实例属性,每个实例独有

# 使用类
my_car = Car("red")
print(my_car.wheels)  # 输出: 4
print(my_car.color)   # 输出: red

例子 3:私有属性和命名风格

class Account:
    def __init__(self, owner, amount):
        self.owner = owner
        self.__amount = amount   # 私有属性

    def show_balance(self):
        return f"{self.owner} has ${self.__amount} in the account."

# 使用类
account = Account("John", 500)
print(account.show_balance())  # John has $500 in the account.

例子 4:类方法和静态方法

class Circle:
    pi = 3.14  # 类属性

    def __init__(self, radius):
        self.radius = radius

    @classmethod
    def from_diameter(cls, diameter):
        return cls(diameter / 2)

    @staticmethod
    def is_valid_radius(radius):
        return radius > 0

# 使用类
circle = Circle.from_diameter(10)
print(circle.radius)  # 输出: 5.0
print(Circle.is_valid_radius(5))  # 输出: True

例子 5:继承

class Animal:
    def speak(self):
        return "Some sound"

class Cat(Animal):
    def speak(self):
        return "Meow"

# 使用类
my_cat = Cat()
print(my_cat.speak())  # 输出: Meow

例子 6:多态和抽象类

from abc import ABC, abstractmethod

class Animal(ABC):
    @abstractmethod
    def speak(self):
        pass

class Dog(Animal):
    def speak(self):
        return "Woof!"

class Cat(Animal):
    def speak(self):
        return "Meow"

# 使用类
animals = [Dog(), Cat()]
for animal in animals:
    print(animal.speak())  # 输出: Woof! 和 Meow!

例子 7:属性装饰器

class Celsius:
    def __init__(self, temperature=0):
        self._temperature = temperature

    @property
    def temperature(self):
        return self._temperature

    @temperature.setter
    def temperature(self, value):
        if value < -273.15:
            raise ValueError("Temperature below -273.15 is not possible")
        self._temperature = value

# 使用类
weather = Celsius()
weather.temperature = 25
print(weather.temperature)  # 输出: 25
try:
    weather.temperature = -300
except ValueError as e:
    print(e)  # 输出: Temperature below -273.15 is not possible

例子 8:重载运算符

class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)

    def __str__(self):
        return f"Vector({self.x}, {self.y})"

# 使用类
v1 = Vector(2, 4)
v2 = Vector(1, 3)
print(v1 + v2)  # 输出: Vector(3, 7)

例子 9:多重继承

class Engine:
    def start(self):
        return "Engine starting"

class Camera:
    def click(self):
        return "Clicking photo"

class Phone(Engine, Camera):
    def make_call(self):
        return "Making call"

# 使用类
smartphone = Phone()
print(smartphone.start())  # 输出: Engine starting
print(smartphone.click())  # 输出: Clicking photo

例子 10:复合

class Engine:
    def start(self):
        return "Engine has been started"

class Car:
    def __init__(self):
        self.engine = Engine()

    def start(self):
        return self.engine.start()

# 使用类
my_car = Car()
print(my_car.start())  # 输出: Engine has been started
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,下面是10个机器学习分算法的Python实例: 1. 决策树分 ```python from sklearn.tree import DecisionTreeClassifier from sklearn.datasets import load_iris iris = load_iris() X, y = iris.data, iris.target clf = DecisionTreeClassifier() clf.fit(X, y) ``` 2. 支持向量机分 ```python from sklearn.svm import SVC from sklearn.datasets import load_iris iris = load_iris() X, y = iris.data, iris.target clf = SVC() clf.fit(X, y) ``` 3. K近邻分 ```python from sklearn.neighbors import KNeighborsClassifier from sklearn.datasets import load_iris iris = load_iris() X, y = iris.data, iris.target clf = KNeighborsClassifier() clf.fit(X, y) ``` 4. 朴素贝叶斯分 ```python from sklearn.naive_bayes import GaussianNB from sklearn.datasets import load_iris iris = load_iris() X, y = iris.data, iris.target clf = GaussianNB() clf.fit(X, y) ``` 5. 随机森林分 ```python from sklearn.ensemble import RandomForestClassifier from sklearn.datasets import load_iris iris = load_iris() X, y = iris.data, iris.target clf = RandomForestClassifier() clf.fit(X, y) ``` 6. AdaBoost分 ```python from sklearn.ensemble import AdaBoostClassifier from sklearn.datasets import load_iris iris = load_iris() X, y = iris.data, iris.target clf = AdaBoostClassifier() clf.fit(X, y) ``` 7. 梯度提升分 ```python from sklearn.ensemble import GradientBoostingClassifier from sklearn.datasets import load_iris iris = load_iris() X, y = iris.data, iris.target clf = GradientBoostingClassifier() clf.fit(X, y) ``` 8. 神经网络分 ```python from sklearn.neural_network import MLPClassifier from sklearn.datasets import load_iris iris = load_iris() X, y = iris.data, iris.target clf = MLPClassifier() clf.fit(X, y) ``` 9. LDA分 ```python from sklearn.discriminant_analysis import LinearDiscriminantAnalysis from sklearn.datasets import load_iris iris = load_iris() X, y = iris.data, iris.target clf = LinearDiscriminantAnalysis() clf.fit(X, y) ``` 10. QDA分 ```python from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis from sklearn.datasets import load_iris iris = load_iris() X, y = iris.data, iris.target clf = QuadraticDiscriminantAnalysis() clf.fit(X, y) ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

superdont

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值