이 페이지는 최신 브라우저(SharedArrayBuffer 지원)가 필요합니다. Chrome, Edge, Firefox 또는 Safari를 최신 버전으로 업데이트해 주세요.
English
A class is a blueprint
- A class defines a new kind of thing — a user-defined type.
- An object is one item made from that class.
- One
Dogclass can make many dog objects, each with its own data.

English
init and attributes
__init__is a special method that runs when you make an object.selfrefers to the object being made.- Values stored on
selfare the object's attributes (its data).
English
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(2, 5)
print(p.x)
print(p.y)
English
Methods
- A method is a function defined inside a class.
- An instance method conventionally names its first parameter
self; it refers to the object the method works on. - Call it with a dot:
object.method().
English
class Greeter:
def __init__(self, name):
self.name = name
def hello(self):
return "Hi, " + self.name
g = Greeter("Sam")
print(g.hello())
English
Enumerated types
- An enumerated type is a fixed set of named values.
from enum import Enumlets you define one as a class.- It is clearer than using loose numbers like
1,2,3.
English
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
print(Color.GREEN)
print(Color.GREEN.value)
English
In Cambridge pseudocode
- A
CLASSblock lists its data and aNEWconstructor.
CLASS Point
PRIVATE X : INTEGER
PRIVATE Y : INTEGER
PUBLIC PROCEDURE NEW(startX : INTEGER, startY : INTEGER)
X ← startX
Y ← startY
ENDPROCEDURE
ENDCLASS
DECLARE p : Point
p ← NEW Point(2, 5)
English
Common mistakes
- Instance methods conventionally take
selfas their first parameter. __init__runs automatically when you create an object.
English
Now you try
- Define each class with
__init__and any methods it needs. - Press Check answer to test your code.
난이도 3/5 · 200코인 + 오늘 첫 완료 시 작은 보너스 추가
Define a class Dog whose __init__ takes name 및 age and stores them as attributes self.name 및 self.age.
출력을 보려면 '실행'을 클릭하세요.
난이도 3/5 · 200코인 + 오늘 첫 완료 시 작은 보너스 추가
Define a class Rectangle with __init__(self, width, height) and a method area(self) that 환원 width * height.
출력을 보려면 '실행'을 클릭하세요.
난이도 3/5 · 200코인 + 오늘 첫 완료 시 작은 보너스 추가
Define a class BankAccount. __init__ 세트 self.balance 부터 0. Add deposit(self, amount) to add money and withdraw(self, amount) to take it away.
출력을 보려면 '실행'을 클릭하세요.