Python에서 클래스는 class
키워드와 클래스 이름을 사용하여 정의됩니다. 클래스 내에서 속성과 방법을 모두 정의 할 수 있습니다.
속성은 클래스 인스턴스와 관련된 데이터를 저장하는 변수입니다. 클래스 본문 (클래스 속성) 또는 __init__
메소드 (인스턴스 속성)와 같은 메소드 내에서 직접 정의 할 수 있습니다. __init__
메소드는 클래스 인스턴스가 생성 될 때 호출되는 특수 메소드입니다. 일반적으로 클래스의 속성을 초기화하는 데 사용됩니다.
다음은 수업에서 속성을 정의하는 예입니다.
<code class="python">class Person: # Class attribute species = "Homo sapiens" # Instance attribute defined in the __init__ method def __init__(self, name, age): self.name = name self.age = age</code>
방법은 클래스의 동작을 정의하는 클래스 내에서 정의 된 기능입니다. 클래스의 속성에 액세스하고 작업을 수행 할 수 있습니다. 방법은 일반 함수와 유사하게 정의되지만 클래스 본문 내에서 들여 쓰기됩니다.
다음은 수업에서 방법을 정의하는 예입니다.
<code class="python">class Person: def __init__(self, name, age): self.name = name self.age = age # Method to introduce the person def introduce(self): return f"My name is {self.name} and I am {self.age} years old."</code>
이 예에서 introduce
사람을 소개하는 문자열을 반환하는 메소드입니다.
파이썬에는 클래스 내에서 정의 할 수있는 두 가지 유형의 속성이 있습니다 : 인스턴스 속성 및 클래스 속성.
인스턴스 속성은 클래스의 각 인스턴스에만 해당됩니다. self
키워드를 사용하여 __init__
방법 또는 클래스의 다른 방법 내부에서 정의됩니다. 클래스의 각 인스턴스는 인스턴스 속성에 대해 다른 값을 가질 수 있습니다.
예를 들어:
<code class="python">class Person: def __init__(self, name): self.name = name # Instance attribute person1 = Person("Alice") person2 = Person("Bob") print(person1.name) # Outputs: Alice print(person2.name) # Outputs: Bob</code>
클래스 속성은 클래스의 모든 인스턴스 중에서 공유됩니다. 그것들은 어떤 방법 외부의 클래스 본문에서 직접 정의됩니다. 클래스 속성으로의 변경은 클래스의 모든 인스턴스에 영향을 미칩니다.
예를 들어:
<code class="python">class Person: species = "Homo sapiens" # Class attribute def __init__(self, name): self.name = name person1 = Person("Alice") person2 = Person("Bob") print(person1.species) # Outputs: Homo sapiens print(person2.species) # Outputs: Homo sapiens Person.species = "New Species" print(person1.species) # Outputs: New Species print(person2.species) # Outputs: New Species</code>
이 예에서 species
Person
클래스의 모든 인스턴스에서 공유되는 계급 속성입니다.
상속은 객체 지향 프로그래밍의 기본 개념으로 클래스 (서브 클래스 또는 파생 클래스라고 함)가 다른 클래스 (슈퍼 클래스 또는 기본 클래스라고 함)의 속성 및 메소드를 상속 할 수 있도록합니다. 이를 통해 코드 재사용 및 기존 클래스를 기반으로보다 구체적인 유형의 객체를 생성 할 수 있습니다.
파이썬에서 상속을 사용하려면 서브 클래스 정의의 클래스 이름 후에 괄호 안의 슈퍼 클래스를 지정합니다. 예는 다음과 같습니다.
<code class="python">class Animal: def __init__(self, species): self.species = species def make_sound(self): pass # This method is intended to be overridden by subclasses class Dog(Animal): def __init__(self, name): super().__init__("Canis familiaris") # Call the __init__ method of the superclass self.name = name def make_sound(self): return "Woof!" class Cat(Animal): def __init__(self, name): super().__init__("Felis catus") # Call the __init__ method of the superclass self.name = name def make_sound(self): return "Meow!"</code>
이 예에서 Dog
Cat
Animal
의 서브 클래스입니다. 그들은 species
속성을 물려 받고 특정 동작을 제공하기 위해 make_sound
방법을 무시할 수 있습니다.
상속을 사용하여 더 복잡한 클래스 계층 구조를 만들고 클래스가 둘 이상의 슈퍼 클래스에서 상속 될 수있는 여러 상속을 구현할 수 있습니다.
파이썬 클래스 내에서 방법을 조직하는 것은 효과적으로 가독성과 유지 가능성에 중요합니다. 모범 사례는 다음과 같습니다.
calculate
, update
, fetch
)을 시작하고 메소드가하는 일에 대해 구체적으로하십시오.방법 순서 :
__init__
, __str__
, __repr__
등과 같은 특수 방법으로 시작하십시오._
로 시작하는 방법)을 포함합니다.__
)을 포함하십시오.잘 조직 된 수업의 예는 다음과 같습니다.
<code class="python">class BankAccount: def __init__(self, account_number, balance=0): self.account_number = account_number self.balance = balance def deposit(self, amount): if amount > 0: self.balance = amount return True return False def withdraw(self, amount): if 0 0 def __str__(self): return f"Account {self.account_number}: Balance = ${self.balance}"</code>
이 예에서는 특수 메소드가 먼저 나오고 ( __init__
, __str__
) 공개 방법 ( deposit
, withdraw
, get_balance
) 및 마지막으로 보호 된 방법 ( _validate_transaction
)이 이어집니다. 각 방법은 간결하며 명확한 목적을 가지고 있습니다.
위 내용은 파이썬 클래스에서 속성과 방법을 어떻게 정의합니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!