|

楼主 |
发表于 2021-2-15 14:24:32
|
显示全部楼层
本帖最后由 Python初学者8号 于 2021-2-15 14:33 编辑
5 2021年2月15日14:14:45
新增加的理解,哈哈,如代码- class Dog(object):
- def __init__(self, variety, age, height, weight):
- self.variety = variety
- self.age = age
- self.height = height
- self.weight = weight
-
- def property(self):
- print(self.variety)
- print('%d years old' %self.age)
- print('%d cm' %self.height)
- print('%d kg' %self.weight)
- print('This kind of dog can destory things.')
- print('This kind of dog can eat the food.')
- print("This kind of dog maybe bite people.")
- print('''
- ''')
- husky = Dog('Husky', 9, 55, 25)
- borderCollie = Dog('Border Collie', 12, 49, 12)
- husky.property()
- borderCollie.property()
复制代码- a = 1
- class Student():
- global a
- a = 2
- def __init__(self, name, score):
- self.name = name
- self.score = score
- def get_grade(self):
- if self.score >= 90:
- return 'A'
- elif self.score >= 60:
- return 'B'
- else:
- return 'C'
- def f1(self):
- a = 3
- b = 2
- print(a,b)
-
- bart = Student('syd',88)
- bart.get_grade()
- bart.f1()
复制代码
这么理解一下:
我们想要让每个内部的method都使用在实例之内但是又在函数之外的外部变量的时候,就必须找参数啊。
就像f1这个函数,首先找一下f1内部的局部变量,然后找不到a的时候就去看init中有没有(此时,这个变量必须是前缀self.),再没有的话,再看看有没有全局变量
- a = 1
- class Student():
- global a
- a = 2
- def __init__(self, name, score,a):
- self.name = name
- self.score = score
- self.a = a
- def get_grade(self):
- if self.score >= 90:
- return 'A'
- elif self.score >= 60:
- return 'B'
- else:
- return 'C'
- def f1(self):
- b = 2
- print(self.a,b)
-
- bart = Student('syd',88,3)
- bart.get_grade()
- bart.f1()
复制代码
所以这么总结吧,在类的方法中使用变量考虑两个方向,
1.一个是不加self.的变量。
函数在使用的时候会现在内部寻找(即为局部变量),找不到了再看有没有外部的全局变量。
当全局和局部的时候,那就是强龙不压地头蛇
它是一种相对来说的公共的参数,因为每个类在创建的时候就有,但是又是可以改变的(只有global的时候)
2 一个是加self.的变量
这个类变量的出现让每个类有独一无二的属性,我个人理解是避免在类的外部定义 一大堆的外部变量然后又在类中使用全局,多此一举啊!
所以就这样做,这样做很高级
设想一下,当不这么设计类这种东西的话,我们写程序就这样写
- a = 1
- class Student():
- global a
- def get_grade(self):
- if self.score >= 90:
- return 'A'
- elif self.score >= 60:
- return 'B'
- else:
- return 'C'
- def f1(self):
- b = 2
- print(a,b)
-
-
- ##bart = Student('syd',88,3)
- bart = Student()
- ##bart.get_grade()
- bart.f1()
复制代码
如果这样写,当然实现了的是逻辑的封装,那么这个和函数有什么区别吗?区别只是可以调用内部函数而已(当然可以在def fucntion后使用return f1,f2,f3实现)
但是这样的效率太低了,如果有两个实例的话,那么不是公用a吗?
所以不用这样的方法
不得不说类的设计还是很好 的
|
|