
objects of a class
object가 어떤 클래스의 객체인지 관계를 설명할때 사용
class Cookie:
pass
a = Cookie() # a는 object, Cookie의 instance
b = Cookie() # b는 object, Cookie의 instance
클래스 안에서 구현하는 함수 ⇒ 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)
Functions for integers
random.randint(a, b)
a <= N <= b. randrange(a, b+1)random.randrange(start, stop[, step])
range(start, stop, step)string.zfill(len)
클래스 안의 변수를 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해도 같음!
{price}{0},{}. 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):, 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.