Class & Method

旅人·2023년 6월 15일
0

Code

class Planet:
    
    shape = 'round'
    
    def __init__(self, name, radius, gravity, system):
        self.name = name
        self.radius = radius
        self.gravity = gravity
        self.system = system
        
    def __str__(self):
        return f'name : {self.name}, radius : {self.radius}, gravity : {self.gravity}, system : {self.system}'
    
    def orbit(self):
        return f'{self.name} is orbiting in the {self.system}'
    
    @classmethod
    def commons(cls):
        return f'All planetes are {cls.shape}'
    
    @staticmethod
    def spin(speed = '2000 miles per hour'):
        return f'The planet spins and spins at {speed}'
        
hoth = Planet('Hoth', 200000, 5.5, 'Hoth System')
print(hoth)

naboo = Planet('Naboo', 300000, 8, 'Naboo System')
print(naboo)
print(naboo.orbit())
print(Planet.orbit(naboo)) # Naboo is orbiting in the Naboo System

print(Planet.shape)
print(naboo.shape)

print(Planet.commons())
print(hoth.commons())

print(Planet.spin()) # The planet spins and spins at 2000 miles per hour
print(hoth.spin('a very high speed')) # The planet spins and spins at a very high speed



self와 정적 메서드, 매직 메서드에 관해서는 아래 HP 참고


참고

https://www.youtube.com/watch?v=H--VDcDSHdg&list=PL4cUxeGkcC9idu6GZ8EU_5B6WpKTdYZbK&index=16

(Python의 self)
https://velog.io/@magnoliarfsit/RePython-1.-self-%EC%9D%B4%ED%95%B4%ED%95%98%EA%B8%B0

(@staticmethod @classmethod 차이)
https://wikidocs.net/21054

(magic method)
https://tibetsandfox.tistory.com/42

profile
一期一会

0개의 댓글