面向对象

面向对象

  • 通过字典存储属性
studA = {
    "name":"yuhaohong",
    "age":"23",
    "birthday":"2017-03-17"
}

  • 类名
  • 属性
  • 方法
class 类名:
    方法列表
  • 定义一个类:
    • ==在类中定义的方法,第一个参数都要写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)
  • __init__方法
    • ==创建对象的时候自动执行,类似于构造方法==
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

你可能感兴趣的:(面向对象)