[파이썬300제] 251~276 정리

·2023년 10월 17일

Python 300

목록 보기
5/5
post-thumbnail

1. Class vs Instance vs Object

  • Object
    • Everything in python is an object
    • built-in data types(e.g. integers, strings, lists…) & user-defined data types(e.g. classes)
    • An object consists of:
      • State: It is represented by the attributes of an object. It also reflects the properties of an object.
      • Behavior: It is represented by the methods of an object. It also reflects the response of an object to other objects.
      • Identity: It gives a unique name to an object and enables one object to interact with other objects.
  • Class
    • a collection of objects(instances)
    • attributes 는 클래스에 속한 variables
    • attributes are always public and can be accessed using the dot(.) Eg.:my_class.my_attribute
  • Instance
    • objects of a class

    • object가 어떤 클래스의 객체인지 관계를 설명할때 사용

      class Cookie:
      	pass
      
      a = Cookie() # a는 object, Cookie의 instance
      b = Cookie() # b는 object, Cookie의 instance

2. Constructor vs Method

  • Constructor
    • the init() method
    • always called when an object is created
    • types
      • default constructor : doesn’t accepts any arguments(has only one argument → self)
      • parameterized constructor : takes its first argument as a reference to the instance being constructed known as self and the rest of the arguments are provided by the programmer
  • Method
    • 클래스 안에서 구현하는 함수 ⇒ tied to objects or classes(need an object or class instance to be invoked)

    • 첫번째 매개변수의 이름은 클래스의 인스턴스 자신 → self

      # 1.
      
      class GeekforGeeks:
      
      # default constructor
      		def __init__(self):
              self.geek = "GeekforGeeks"
      
      # a method for printing data members
          def print_Geek(self):
              print(self.geek)
      
      obj = GeekforGeeks()
      
      ------------------------------------------------------------
      
      # 2.
      
      class Addition:
          first = 0
          second = 0
          answer = 0
      
      # parameterized constructor
      		def __init__(self, f, s):
              self.first = f
              self.second = s
      
      obj1 = Addition(1000, 2000)

3. random() function

  • Functions for integers

  • random.randint(ab)

    • Return a random integer N such that a <= N <= b.
    • Alias for randrange(a, b+1)
  • random.randrange(startstop[, step])

    • Return a randomly selected element from range(start, stop, step)

4. zfill() method

  • string.zfill(len)

    • adds zeros (0) at the beginning of the string, until it reaches the specified length
    • len < len(str) : no filling is done
  • 클래스 안의 변수를 method(constructor)안에서 사용하려면 “클래스이름.변수명” 이렇게 사용해야함!

    class Hello:
        # class variable
        greeting_count = 0
    
    		def __init__(self, name):
    			self.name = name
    
    			print(f"Hello, {name}!")
    
    			# greeting_count += 1       이렇게 사용못함
    			Hello.greeting_count += 1 # 이렇게 사용해야함!
    
    K = Hello("K")
    print(Hello.greeting_count) #greeting_count 변수 불러오기
    J = Hello("J")
    print(J.greeting_count)  
    #J가 Hello 클래스 instance니까 J.greeting_count해도 같음!

5. String format() method

  • formats the specified value(s) and insert them inside the string's placeholder.
    • The placeholder is defined using curly brackets: {}
      • The placeholders can be identified using named indexes {price}
      • numbered indexes {0},
      • or even empty placeholders {}.
       txt1 = "My name is {fname}, I'm {age}".format(fname = "John", age = 36)
        txt2 = "My name is {0}, I'm {1}".format("John",36)
        txt3 = "My name is {}, I'm {}".format("John",36)
    • returns the formatted string

    Formatting Types

    • :, Use a comma as a thousand separator

    • Output formatting : f-strings

      universe_age = 13800000000
      print(f"The universe is {universe_age:,} years old.")
      
      #... The universe is 13,800,000,000 years old.
profile
사랑을담아봄

0개의 댓글