跳轉到

8.類別

# Attribute references
class MyClass:
  var = 123
  def method(self):
    return "hello world"
# Instantiation
my_object = MyClass()
# 用 . 來訪問物件的屬性或方法
print(my_object.var) # 123
print(my_object.method()) # hello world

init myself

# no arguments
class MyClass:
  def __init__(self):
    print("do nothing")
my_object = MyClass()
# do nothing

變數初始化

# with arguments
class MyClass:
  def __init__(self, var1, var2):
    self.var1 = var1
    self.var2 = var2
my_object = MyClass(123, 456)
print(my_object.var1) # 123
print(my_object.var2) # 456

Example

class Person:
  bmi = 0.0
  height = 0.0
  weight = 0
  def __init__(self):
    pass
  def ask_person_info(self):
    self.height = float(input("What is your height? (meter) : "))
    self.weight = int(input("What is your weight? (kg) : "))
  def cal_BMI(self):
    self.bmi = round((self.weight / (self.height ** 2)), 2)
    print("Your BMI is " + str(self.bmi))

Test7

Q1. 寫一個 Class,
包含一個變數(str1)以及兩個函式(set_string 和 print_string).
set_string 接受一個字串參數,賦值給 str1。
print_string 印出 str1 的大寫字串
hint: 先宣告一個成員變數,再透過上述兩個函式對該變數做操作。
class Test7:
  def __init__(self):
    self.str1 = ""
  def set_string(self,str1):
    self.str1=str1
  def print_string(self):
    print(self.str1.upper()) 

myClass=Test7()
myClass.set_string('hello world')
myClass.print_string()