Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Classes & Object-Oriented Basics | Functions & Modularity
Introduction to Python with Cursor

bookClasses & Object-Oriented Basics

メニューを表示するにはスワイプしてください

Object-oriented programming (OOP) organizes code by combining data and behavior into objects. Instead of using separate variables and functions, you model real-world concepts through classes.

In Python, a class defines how an object is structured and what it can do.

Defining a Class

A class is a template for creating objects, defined with the class keyword. It specifies what attributes the object has and what it can do.

The special __init__ method runs when a new object is created, letting you set initial data.

For example, a Car class could define attributes like brand and year.

Creating and Using Objects

After defining a class, you create objects (instances) by calling the class like a function with the needed values.

Use dot notation to access attributes, e.g. my_car.brand. Each object stores its own data based on what you provide.

Adding Methods to a Class

Classes can also define behavior through methods — functions written inside the class. Methods let objects act based on their own data. For example, a Car class might have a method that says: "This is a Toyota from 2020."

Methods look like normal functions, but always take self as the first parameter. self refers to the specific object calling the method, giving it access to its own attributes and other methods.

  • self.brand - this object's brand;
  • self.describe() - this object's describe method.

Class vs Instance Variables

Inside a class, you can define:

  • Instance variables: unique to each object (self.brand);
  • Class variables: shared across all objects of that class.

Use instance variables for things like a car's model or year. Use class variables for shared values, like a general category.

Summary

  • Classes define the structure and behavior of objects;
  • Use __init__ to set up an object's data at creation;
  • Create objects by calling the class like a function;
  • Methods add behavior to your objects;
  • self refers to the current object;
  • Class variables are shared; instance variables are unique.
question mark

What does the __init__ method do in a class?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 4.  4

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 4.  4
some-alt