1 类 对象关系
同一个类中的对象拥有相同的属性和方法
类定义了属性和方法
类只有一个,对象有无数个
2 类的设计
先分析需求程序中需要哪些类?
1、类名(大驼峰命名法)
2、属性(特性)
3、方法(行为)
eg:
person类
name、age、height三个属性
run()、eat()两个方法
dog类
coler、name属性
shake()、shout()方法
3 dir内置函数
dir函数传入表示符,可以查看对象内所有的属性和方法
def demo():
print("this is a text")
print(dir(demo))
###########################
['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__',
4 定义类
class
class Cat:
def eat(self):
print("cat like fish")
def drink(self):
print("cat will drink")
tom = Cat()
tom.eat()
tom.drink()
class Cat:
def eat(self):
print("cat like fish")
def drink(self):
print("cat will drink")
tom = Cat()
tom.eat()
tom.drink()
print(tom) # 会显示哪一类
print(id(tom))
print("%d" % id(tom)) # %d 十进制
print("%x" % id(tom)) # %x 十六进制
####################################################
cat like fish
cat will drink
<__main__.Cat object at 0x7fbabf39d5c0>
140440048883136 十进制
140440048883136 十进制
7fbabf39d5c0 十六进制
类只有一个,但可以创建不同的对象