【Python 学习笔记】python class basic

Can you teach me python class?

Here's a basic introduction to classes in Python.

What is a Class?

A class in Python is a blueprint for creating objects. Objects are instances of classes, and they can have attributes (variables) and methods (functions) associated with them.

Defining a Class

You can define a class using the class keyword. Here's an example of a simple class:

class Dog:
    # Class attribute
    species = "Canis familiaris"

    # Initializer / Instance attributes
    def __init__(self, name, age):
        self.name = name
        self.age = age

    # Instance method
    def description(self):
        return f"{self.name} is {self.age} years old"

    # Another instance method
    def speak(self, sound):
        return f"{self.name} says {sound}"

Creating an Instance

You create an instance of a class by calling the class as if it were a function, and passing any arguments that the __init__ method requires:

my_dog = Dog(name="Buddy", age=3)

Accessing Attributes and Methods

You can access the attributes and methods of an instance using dot notation:

print(my_dog.name)        # Output: Buddy
print(my_dog.age)         # Output: 3
print(my_dog.species)     # Output: Canis familiaris
print(my_dog.description())  # Output: Buddy is 3 years old
print(my_dog.speak("Woof"))  # Output: Buddy says Woof

Inheritance

Classes can inherit from other classes. This allows you to create a hierarchy of classes that share a set of attributes and methods:

class GoldenRetriever(Dog):
    def speak(self, sound="Bark"):
        return super().speak(sound)

In this example, GoldenRetriever is a subclass of Dog and inherits its attributes and methods. It also overrides the speak method to provide a default sound.

my_dog = GoldenRetriever(name="Buddy", age=3)
print(my_dog.speak())  # Output: Buddy says Bark

Summary

  • Class: A blueprint for creating objects.
  • Object: An instance of a class.
  • Attributes: Variables that belong to an object.
  • Methods: Functions that belong to an object.
  • Inheritance: A way to create a new class using details of an existing class.

In Python classes, self is a reference to the current instance of the class. It is used to access variables that belong to the class, ensuring that each instance can maintain its own data.

self must be the first parameter of any method in the class (including the __init__ method). You can use any other name, but self is a widely accepted convention)

When you create an instance of Dog, like this:

my_dog = Dog(name="Buddy", age=3)

The __init__ method is called, with self referring to the new instance (my_dog).

 "Answer Generated by OpenAI's ChatGPT"

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值