Primrose Docs
  • Home
    • ⛓️Blockchain
      • Avalanche
        • What is AVAX?
      • Ethereum
        • Ethereum Cancun Upgrade Explained(draft)
        • go-ethereum: gas estimate
        • Blockchain Transaction Lifecycle
        • Mempool
        • Gas optimization in Solidity, Ethereum
      • Solidity DeepDive
        • Meta transaction
        • solidity: patterns
        • UUPS vs Transparent
        • Solidity Interface
        • Smart contract storage
        • ERC-2981 Contract
        • Solidity modifier
        • Solidity delete keyword
        • How To Make NFTs with On-Chain Metadata - Hardhat and JavaScript
        • How to Build "Buy Me a Coffee" DeFi dapp
        • How to Develop an NFT Smart Contract (ERC 721) with Alchemy
        • Upgradeable Contract
        • Smart Contract Verification
      • Common
        • Eigenlayer
        • MultiSig(draft)
        • Chain-Based Proof-of- Stake, BFT-Style Proof-of-Stake
        • Byzantine Fault Tolerance
        • Zero-knowledge
        • Hierarchical Deterministic Wallet
        • Maker DAO
        • Defi
        • Uniswap
        • IBC
        • Cosmos
        • Gossip Protocol
        • Tendermint
        • UTXO vs Account
        • Blockchain Layer
        • Consensus Algorithm
        • How does mining work?
        • Immutable Ledger
        • SHA256 Hash
        • Filecoin
        • IPFS - InterPlanetary File System
        • IPFS와 파일코인
        • Livepeer
        • Layer 0
      • Bitcoin
        • BIP for HD Wallet
        • P2WPKH
        • Segwit vs Native Segwit
    • 📖Languages
      • Javascript/Typescript
        • Hoisting
        • This value in Javascript
        • Execution Context
        • About Javscript
        • tsconfig.json
        • Nest js Provider
        • 'return await promise' vs 'return promise'
      • Python
        • Pythonic
        • Python: Iterable, Iterator
        • Uvicorn & Gunicorn
        • WSGI, ASGI
        • Python docstring
        • Decorator in Python
        • Namespace in Python
        • Python Method
      • Go
        • GORM+MySQL Connection Pool
        • Context in golang
        • How to sign Ethereum EIP-1559 transactions using AWS KMS
        • Mongo DB in golang(draft)
        • Golang HTTP Package
        • Panic
        • Golang new/make
        • golang container package
        • errgroup in golang
        • Generic Programming in Golang
        • Goroutine(draft)
    • 📝Database
      • MongoDB in golang
      • Nested loop join, Hash join
      • DB Query plan
      • Index
      • Optimistic Lock Pessimistic Lock
    • 💻Computer Science
      • N+1 query in go
      • Web server 를 구성할 때 Thread, Process 개수를 어떻게 정할 것인가?
      • CAP
      • Socket programming
      • DNS, IP
      • URL, URI
      • TLS과 SSL
      • Caching(draft)
      • Building Microservices: Micro Service 5 Deploy Principle
      • Red Black Tree
      • AOP
      • Distributed Lock
      • VPC
      • Docker
      • All about Session and JWT
      • Closure
      • Singleton Pattern
      • TCP 3 way handshake & 4 way handshake
      • Race Condition
      • Process Address Space 
      • Call by value, Call by reference, Call by assignment
      • Zookeeper, ETCD
      • URL Shortening
      • Raft consensus
      • Sharding, Partitioning
    • 📒ETC
      • K8S SIGTERM
      • SQS
      • Git Branch Strategy: Ship / Show / Ask
      • Kafka
      • Redis Data Types
      • CI/CD
      • How does Google design APIs?
      • Minishell (42 cursus)
      • Coroutine & Subroutine
      • Redis
Powered by GitBook
On this page
  • Instance Method
  • Class Method
  • Static Method
  1. Home
  2. Languages
  3. Python

Python Method

Instance Method

클래스에 아무 decorator 없이 method를 선언하면 해당 method는 instance method로 취급이 되며, 첫 번째 parameter로 클래스의 instance가 넘어오게 된다.

이 첫 번째 parameter의 이름은 self라고 하며, self.attribute …를 통해 instance/class 속성에 접근하거나 instance/class method를 호출할 수 있다.

class Counter:

    def __init__(self, value=0):
        self.value = value

    def increment(self, delta=1):
        self.value += delta

    def decrement(self, delta=1):
        self.value -= delta

Class Method

@classmethod decorator를 사용해서 클래스에 method를 선언하면

해당 method는 class method가 되며, 첫 번째 parameter로 self가 아닌 cls라는 이름으로 클래스 자체가 넘어오게 된다.

클래스 method는 이 cls를 통해 클래스 속성에 접근하거나, 다른 class method를 호출할 수 있다.

하지만, instance method와 달리 instance 속성에 접근하거나 다른 instance method를 호출하는 것은 불가능하다.

Python에서는 생성자 overloading을 지원하기 때문에, Class method는 주로 Factory method를 작성할 때 유용하게 사용된다.

class Counter:

    def __init__(self, value=0):
        self.value = value

    def increment(self, delta=1):
        self.value += delta

    def decrement(self, delta=1):
        self.value -= delta

    @classmethod
    def newCounterFromTuple(cls, tup):
        return cls(tup[0])

    @classmethod
    def newCounterFromArray(cls, arr):
        return cls(arr.pop())

Static Method

@staticmethod decorator를 사용해서 method를 선언하면 해당 method는 정적 method가 된다.

정적 method는 instance method나 class method와 달리 첫 번째 parameter가 할당되지 않는다.

따라서 정적 method 내에서는 instance/class 속성에 접근하거나, instance/class method를 호출하는 것이 불가능하다.

바꾸어말하면, 접근할 필요가 없을 때 사용하면 되기 때문에, 주로 utility method를 작성할 때 유용하다.

class Counter:

    def __init__(self, value=0):
        self.value = value

    def increment(self, delta=1):
        self.value += delta

    def decrement(self, delta=1):
        self.value -= delta

    @classmethod
    def newCounterFromTuple(cls, tup):
        return cls(tup[0])

    @classmethod
    def newCounterFromArray(cls, arr):
        return cls(arr.pop())

    @staticmethod
    def PrintInformation():
        print("This is a counter")
PreviousNamespace in PythonNextGo

Last updated 1 year ago

📖