面向?qū)ο?/h3>
- 通過字典存儲屬性
studA = {
"name":"yuhaohong",
"age":"23",
"birthday":"2017-03-17"
}
類
- 類名
- 屬性
- 方法
class 類名:
方法列表
- 定義一個類:
- ==在類中定義的方法,第一個參數(shù)都要寫self==
class Dog:
def bark(self):
print('wang wang ~')
- 創(chuàng)建一個對象
dog = Dog()
dog.bark()
- 添加屬性
dog = Dog()
dog.weight = 5
dog.color = 'yellow'
- 獲取屬性
print(dog.weight)
- 在方法中修改屬性
class Cat:
def eat(self):
print('吃魚')
self.weight += 1
- 直接修改屬性
cat = Cat()
cat.weight = 1o
cat.eat()
cat.weight += 5
print(cat.weight)
- __init__方法
- ==創(chuàng)建對象的時候自動執(zhí)行,類似于構(gòu)造方法==
class Dog:
def __init__(slef):
self.weight = 5;
self.color='yellow'
class Cat:
def __init__(self,weight,color):
self.weight = weight
self.color = color
- self
- ==程序中必須使用self,不然程序會崩潰==
080808
studA = {
"name":"yuhaohong",
"age":"23",
"birthday":"2017-03-17"
}
class 類名:
方法列表
- ==在類中定義的方法,第一個參數(shù)都要寫self==
class Dog:
def bark(self):
print('wang wang ~')
dog = Dog()
dog.bark()
dog = Dog()
dog.weight = 5
dog.color = 'yellow'
print(dog.weight)
class Cat:
def eat(self):
print('吃魚')
self.weight += 1
cat = Cat()
cat.weight = 1o
cat.eat()
cat.weight += 5
print(cat.weight)
- ==創(chuàng)建對象的時候自動執(zhí)行,類似于構(gòu)造方法==
class Dog:
def __init__(slef):
self.weight = 5;
self.color='yellow'
class Cat:
def __init__(self,weight,color):
self.weight = weight
self.color = color
- ==程序中必須使用self,不然程序會崩潰==
080808